<commit_before>(function() {

QUnit.config.testTimeout = 200;

var sandbox;

module("Oasis");

test("Assert not file://", function() {
  ok(window.location.protocol !== 'file:', "Please run the tests using a web server of some sort, not file://");
});

test("Assert browser satisfies minimum requirements", function() {
  var iframe = document.createElement('iframe');

  iframe.sandbox = 'allow-scripts';
  ok(iframe.getAttribute('sandbox') === 'allow-scripts', "The current version of Oasis requires Sandboxed iframes, which are not supported on your current platform. See http://caniuse.com/#feat=iframe-sandbox");

  ok(typeof MessageChannel !== 'undefined', "The current version of Oasis requires MessageChannel, which is not supported on your current platform. A near-future version of Oasis will polyfill MessageChannel using the postMessage API");
});

module("Oasis.createSandbox", {
  teardown: function() {
    if (sandbox) { sandbox.terminate(); }
    Oasis.reset();
  }
});

test("assertion: must register package", function() {
  raises(function() {
    sandbox = Oasis.createSandbox({
      url: "fixtures/index.js"
    });
  }, Error, "Creating a card from an unregistered package fails");
});

test("assertion: must provide capabilities when registering a package", function() {
  raises(function() {
    Oasis.register({
      url: 'fixtures/index.js'
    });
  }, Error, "Registering a package without capabilities fails");
});

test("returns a sandbox with an iframe element", function() {
  Oasis.register({
    url: "fixtures/index.js",
    capabilities: []
  });

  sandbox = Oasis.createSandbox({
    url: "fixtures/index.js"
  });

  ok(sandbox.el instanceof window.HTMLIFrameElement, "A new iframe was returned");
});

test("service is notified about ports created for a card", function() {
  Oasis.register({
    url: "fixtures/index.js",
    capabilities: ['testData']
  });

  stop();

  var DataService = Oasis.Service.extend({
    initialize: function(port, capability) {
      start();
      equal(this.sandbox, sandbox);
      equal(capability, 'testData');
    }
  });

  sandbox = Oasis.createSandbox({
    url: "fixtures/index.js",
    services: {
      testData: DataService
    }
  });

  document.body.appendChild(sandbox.el);
});

test("service - card can communicate with the environment through a port", function() {
  Oasis.register({
    url: "fixtures/assertions.js",
    capabilities: ['assertions']
  });

  stop();

  var AssertionsService = Oasis.Service.extend({
    initialize: function(port, capability) {
      equal(capability, 'assertions', "precond - capability is the assertions service");

      port.on('ok', function(data) {
        start();
        equal(data, 'success', "The card was able to communicate back");
      });
    }
  });

  sandbox = Oasis.createSandbox({
    url: "fixtures/assertions.js",
    services: {
      assertions: AssertionsService
    }
  });

  sandbox.start();
});

test("service - card can communicate with the environment through a port with the environment shorthand for events", function() {
  Oasis.register({
    url: "fixtures/assertions.js",
    capabilities: ['assertions']
  });

  stop();

  var AssertionsService = Oasis.Service.extend({
    events: {
      ok: function(data) {
        start();
        equal(data, 'success', "The card was able to communicate back");
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: "fixtures/assertions.js",
    services: {
      assertions: AssertionsService
    }
  });

  sandbox.start();
});

test("service - card can communicate with the environment through a port with the card shorthand for events", function() {
  Oasis.register({
    url: "fixtures/assertions_shorthand.js",
    capabilities: ['assertions']
  });

  stop();

  var AssertionsService = Oasis.Service.extend({
    events: {
      ok: function(data) {
        equal(data, 'success', "The card was able to communicate back");

        this.send('ping');
      },

      pong: function() {
        this.request('ping').then(function(response) {
          start();
          equal(response, "pong");
        });
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: "fixtures/assertions_shorthand.js",
    services: {
      assertions: AssertionsService
    }
  });

  sandbox.start();
});

test("shorthand - card can communicate with the environment through a port", function() {
  stop();

  sandbox = Oasis.createSandbox({
    url: "fixtures/assertions.js",
    capabilities: ['assertions']
  });

  sandbox.connect('assertions').then(function(port) {
    port.on('ok', function(data) {
      start();
      equal(data, 'success', "The card was able to communicate back");
    });
  });

  document.body.appendChild(sandbox.el);
});

test("environment can communicate with the card through a port", function() {
  Oasis.register({
    url: "fixtures/to_environment.js",
    capabilities: ['pingpong']
  });

  stop();

  var PingPongService = Oasis.Service.extend({
    initialize: function(port, capability) {
      equal(capability, 'pingpong', "precond - capability is the pingpong service");

      port.on('pong', function(data) {
        start();
        equal(data, "PONG", "Got pong from the child");
      });

      port.send('ping', "PONG");
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/to_environment.js',
    services: {
      pingpong: PingPongService
    }
  });

  document.body.appendChild(sandbox.el);
});

test("environment can communicate with the card through a port with a shorthand", function() {
  Oasis.register({
    url: "fixtures/to_environment.js",
    capabilities: ['pingpong']
  });

  stop();

  var PingPongService = Oasis.Service.extend({
    events: {
      pong: function(data) {
        start();
        equal(data, "PONG", "Got pong from the child");
      }
    },

    initialize: function(port) {
      port.send('ping', "PONG");
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/to_environment.js',
    services: {
      pingpong: PingPongService
    }
  });

  document.body.appendChild(sandbox.el);
});

test("environment can request a value from a sandbox", function() {
  Oasis.register({
    url: "fixtures/promise.js",
    capabilities: ['promisepong']
  });

  stop();

  var PingPongPromiseService = Oasis.Service.extend({
    initialize: function(port, capability) {
      port.request('ping').then(function(data) {
        start();

        equal(data, 'pong', "promise was resolved with expected value");
      });
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/promise.js',
    services: {
      promisepong: PingPongPromiseService
    }
  });

  document.body.appendChild(sandbox.el);
});

test("sandbox can request a value from the environment", function() {
  Oasis.register({
    url: "fixtures/promise_request_from_environment.js",
    capabilities: ['promisepong']
  });

  stop();

  var PingPongPromiseService = Oasis.Service.extend({
    requests: {
      ping: function(promise) {
        promise.resolve('pong');
      }
    },

    events: {
      testResolvedToSatisfaction: function() {
        start();
        ok(true, "test was resolved to sandbox's satisfaction");
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/promise_request_from_environment.js',
    services: {
      promisepong: PingPongPromiseService
    }
  });

  document.body.appendChild(sandbox.el);
});

test("ports sent to a sandbox can be passed to its child sandboxes", function() {
  Oasis.register({
    url: "fixtures/inception_parent.js",
    capabilities: ['inception']
  });

  stop();

  var InceptionService = Oasis.Service.extend({
    initialize: function(port) {
      port.onRequest('kick', function(promise) {
        promise.resolve('kick');
      });

      port.on('workPlacement', function() {
        start();
        ok(true, "messages between deeply nested sandboxes are sent");
      });
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/inception_parent.js',
    services: {
      inception: InceptionService
    }
  });

  document.body.appendChild(sandbox.el);
});

test("ports sent to a sandbox can be passed to its child sandboxes while supporting a shorthand", function() {
  Oasis.register({
    url: "fixtures/inception_parent.js",
    capabilities: ['inception']
  });

  stop();

  var InceptionService = Oasis.Service.extend({
    requests: {
      kick: function(promise) {
        promise.resolve('kick');
        ok(this instanceof InceptionService, "The callback gets the service instance as `this`");
      }
    },

    events: {
      workPlacement: function() {
        start();
        ok(true, "messages between deeply nested sandboxes are sent");
        ok(this instanceof InceptionService, "The callback gets the service instance as `this`");
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/inception_parent.js',
    services: {
      inception: InceptionService
    }
  });

  document.body.appendChild(sandbox.el);
});

test("When the shorthand form is used for events, they can send events", function() {
  Oasis.register({
    url: "fixtures/peter_pong.js",
    capabilities: ['peterpong']
  });

  stop();

  var PeterPongService = Oasis.Service.extend({
    events: {
      peter: function() {
        this.send('ping');
      },

      pong: function() {
        start();

        ok(true, "Succesfully sent events from event shorthand function");
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/peter_pong.js',
    services: {
      peterpong: PeterPongService
    }
  });

  document.body.appendChild(sandbox.el);
});

test("When the shorthand form is used for events, they can send requests", function() {
  Oasis.register({
    url: "fixtures/peter_pong_request.js",
    capabilities: ['peterpong']
  });

  stop();

  var PeterPongService = Oasis.Service.extend({
    events: {
      peter: function() {
        this.request('ping').then(function(data) {
          start();
          ok(true, "Successfully sent request from event shorthand function");
        });
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/peter_pong_request.js',
    services: {
      peterpong: PeterPongService
    }
  });

  document.body.appendChild(sandbox.el);
});

test("Consumers instances are saved on the Oasis global", function() {
  stop();

  Oasis.register({
    url: "fixtures/consumer.js",
    capabilities: ['assertions']
  });

  var AssertionsService = Oasis.Service.extend({
    events: {
      ok: function() {
        start();
        ok(true, "Consumer was accessed");
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/consumer.js',
    services: {
      assertions: AssertionsService
    }
  });

  document.body.appendChild(sandbox.el);
});

})();
<commit_msg>Change the tests to be sandbox agnostic<commit_after>(function() {

QUnit.config.testTimeout = 200;

var sandbox;

module("Oasis");

test("Assert not file://", function() {
  ok(window.location.protocol !== 'file:', "Please run the tests using a web server of some sort, not file://");
});

test("Assert browser satisfies minimum requirements", function() {
  var iframe = document.createElement('iframe');

  iframe.sandbox = 'allow-scripts';
  ok(iframe.getAttribute('sandbox') === 'allow-scripts', "The current version of Oasis requires Sandboxed iframes, which are not supported on your current platform. See http://caniuse.com/#feat=iframe-sandbox");

  ok(typeof MessageChannel !== 'undefined', "The current version of Oasis requires MessageChannel, which is not supported on your current platform. A near-future version of Oasis will polyfill MessageChannel using the postMessage API");
});

module("Oasis.createSandbox", {
  teardown: function() {
    if (sandbox) { sandbox.terminate(); }
    Oasis.reset();
  }
});

test("assertion: must register package", function() {
  raises(function() {
    sandbox = Oasis.createSandbox({
      url: "fixtures/index.js"
    });
  }, Error, "Creating a card from an unregistered package fails");
});

test("assertion: must provide capabilities when registering a package", function() {
  raises(function() {
    Oasis.register({
      url: 'fixtures/index.js'
    });
  }, Error, "Registering a package without capabilities fails");
});

test("returns a sandbox with an iframe element", function() {
  Oasis.register({
    url: "fixtures/index.js",
    capabilities: []
  });

  sandbox = Oasis.createSandbox({
    url: "fixtures/index.js"
  });

  ok(sandbox.el instanceof window.HTMLIFrameElement, "A new iframe was returned");
});

test("service is notified about ports created for a card", function() {
  Oasis.register({
    url: "fixtures/index.js",
    capabilities: ['testData']
  });

  stop();

  var DataService = Oasis.Service.extend({
    initialize: function(port, capability) {
      start();
      equal(this.sandbox, sandbox);
      equal(capability, 'testData');
    }
  });

  sandbox = Oasis.createSandbox({
    url: "fixtures/index.js",
    services: {
      testData: DataService
    }
  });

  sandbox.start();
});

test("service - card can communicate with the environment through a port", function() {
  Oasis.register({
    url: "fixtures/assertions.js",
    capabilities: ['assertions']
  });

  stop();

  var AssertionsService = Oasis.Service.extend({
    initialize: function(port, capability) {
      equal(capability, 'assertions', "precond - capability is the assertions service");

      port.on('ok', function(data) {
        start();
        equal(data, 'success', "The card was able to communicate back");
      });
    }
  });

  sandbox = Oasis.createSandbox({
    url: "fixtures/assertions.js",
    services: {
      assertions: AssertionsService
    }
  });

  sandbox.start();
});

test("service - card can communicate with the environment through a port with the environment shorthand for events", function() {
  Oasis.register({
    url: "fixtures/assertions.js",
    capabilities: ['assertions']
  });

  stop();

  var AssertionsService = Oasis.Service.extend({
    events: {
      ok: function(data) {
        start();
        equal(data, 'success', "The card was able to communicate back");
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: "fixtures/assertions.js",
    services: {
      assertions: AssertionsService
    }
  });

  sandbox.start();
});

test("service - card can communicate with the environment through a port with the card shorthand for events", function() {
  Oasis.register({
    url: "fixtures/assertions_shorthand.js",
    capabilities: ['assertions']
  });

  stop();

  var AssertionsService = Oasis.Service.extend({
    events: {
      ok: function(data) {
        equal(data, 'success', "The card was able to communicate back");

        this.send('ping');
      },

      pong: function() {
        this.request('ping').then(function(response) {
          start();
          equal(response, "pong");
        });
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: "fixtures/assertions_shorthand.js",
    services: {
      assertions: AssertionsService
    }
  });

  sandbox.start();
});

test("shorthand - card can communicate with the environment through a port", function() {
  stop();

  sandbox = Oasis.createSandbox({
    url: "fixtures/assertions.js",
    capabilities: ['assertions']
  });

  sandbox.connect('assertions').then(function(port) {
    port.on('ok', function(data) {
      start();
      equal(data, 'success', "The card was able to communicate back");
    });
  });

  sandbox.start();
});

test("environment can communicate with the card through a port", function() {
  Oasis.register({
    url: "fixtures/to_environment.js",
    capabilities: ['pingpong']
  });

  stop();

  var PingPongService = Oasis.Service.extend({
    initialize: function(port, capability) {
      equal(capability, 'pingpong', "precond - capability is the pingpong service");

      port.on('pong', function(data) {
        start();
        equal(data, "PONG", "Got pong from the child");
      });

      port.send('ping', "PONG");
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/to_environment.js',
    services: {
      pingpong: PingPongService
    }
  });

  sandbox.start();
});

test("environment can communicate with the card through a port with a shorthand", function() {
  Oasis.register({
    url: "fixtures/to_environment.js",
    capabilities: ['pingpong']
  });

  stop();

  var PingPongService = Oasis.Service.extend({
    events: {
      pong: function(data) {
        start();
        equal(data, "PONG", "Got pong from the child");
      }
    },

    initialize: function(port) {
      port.send('ping', "PONG");
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/to_environment.js',
    services: {
      pingpong: PingPongService
    }
  });

  sandbox.start();
});

test("environment can request a value from a sandbox", function() {
  Oasis.register({
    url: "fixtures/promise.js",
    capabilities: ['promisepong']
  });

  stop();

  var PingPongPromiseService = Oasis.Service.extend({
    initialize: function(port, capability) {
      port.request('ping').then(function(data) {
        start();

        equal(data, 'pong', "promise was resolved with expected value");
      });
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/promise.js',
    services: {
      promisepong: PingPongPromiseService
    }
  });

  sandbox.start();
});

test("sandbox can request a value from the environment", function() {
  Oasis.register({
    url: "fixtures/promise_request_from_environment.js",
    capabilities: ['promisepong']
  });

  stop();

  var PingPongPromiseService = Oasis.Service.extend({
    requests: {
      ping: function(promise) {
        promise.resolve('pong');
      }
    },

    events: {
      testResolvedToSatisfaction: function() {
        start();
        ok(true, "test was resolved to sandbox's satisfaction");
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/promise_request_from_environment.js',
    services: {
      promisepong: PingPongPromiseService
    }
  });

  sandbox.start();
});

test("ports sent to a sandbox can be passed to its child sandboxes", function() {
  Oasis.register({
    url: "fixtures/inception_parent.js",
    capabilities: ['inception']
  });

  stop();

  var InceptionService = Oasis.Service.extend({
    initialize: function(port) {
      port.onRequest('kick', function(promise) {
        promise.resolve('kick');
      });

      port.on('workPlacement', function() {
        start();
        ok(true, "messages between deeply nested sandboxes are sent");
      });
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/inception_parent.js',
    services: {
      inception: InceptionService
    }
  });

  sandbox.start();
});

test("ports sent to a sandbox can be passed to its child sandboxes while supporting a shorthand", function() {
  Oasis.register({
    url: "fixtures/inception_parent.js",
    capabilities: ['inception']
  });

  stop();

  var InceptionService = Oasis.Service.extend({
    requests: {
      kick: function(promise) {
        promise.resolve('kick');
        ok(this instanceof InceptionService, "The callback gets the service instance as `this`");
      }
    },

    events: {
      workPlacement: function() {
        start();
        ok(true, "messages between deeply nested sandboxes are sent");
        ok(this instanceof InceptionService, "The callback gets the service instance as `this`");
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/inception_parent.js',
    services: {
      inception: InceptionService
    }
  });

  sandbox.start();
});

test("When the shorthand form is used for events, they can send events", function() {
  Oasis.register({
    url: "fixtures/peter_pong.js",
    capabilities: ['peterpong']
  });

  stop();

  var PeterPongService = Oasis.Service.extend({
    events: {
      peter: function() {
        this.send('ping');
      },

      pong: function() {
        start();

        ok(true, "Succesfully sent events from event shorthand function");
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/peter_pong.js',
    services: {
      peterpong: PeterPongService
    }
  });

  sandbox.start();
});

test("When the shorthand form is used for events, they can send requests", function() {
  Oasis.register({
    url: "fixtures/peter_pong_request.js",
    capabilities: ['peterpong']
  });

  stop();

  var PeterPongService = Oasis.Service.extend({
    events: {
      peter: function() {
        this.request('ping').then(function(data) {
          start();
          ok(true, "Successfully sent request from event shorthand function");
        });
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/peter_pong_request.js',
    services: {
      peterpong: PeterPongService
    }
  });

  sandbox.start();
});

test("Consumers instances are saved on the Oasis global", function() {
  stop();

  Oasis.register({
    url: "fixtures/consumer.js",
    capabilities: ['assertions']
  });

  var AssertionsService = Oasis.Service.extend({
    events: {
      ok: function() {
        start();
        ok(true, "Consumer was accessed");
      }
    }
  });

  sandbox = Oasis.createSandbox({
    url: 'fixtures/consumer.js',
    services: {
      assertions: AssertionsService
    }
  });

  sandbox.start();
});

})();
<|endoftext|>


<commit_before>"use strict";

// Make jshint happy
/*global describe:false, it:false */

var capisce = require('../lib/capisce.js');
var assert = require("assert");

var LAPSE = 50;

describe('WorkingQueue', function(){
    it('performs jobs passed without parameters', function(done){

        var queue = new capisce.WorkingQueue(1);
        var result = 0;

        queue.perform(function(over) {
            setTimeout(function() {
                result = 1;
                over();
            }, LAPSE);
        });

        queue.whenDone(function() {
            assert.equal(1, result);
            done();
        });
    });

    it('performs jobs passed with parameters', function(done){

        var queue = new capisce.WorkingQueue(1);
        var result = 0;

        queue.perform(function(a, b, over) {
            setTimeout(function() {
                result = a + b;
                over();
            }, LAPSE);
        }, 41, 1);

        queue.whenDone(function() {
            assert.equal(42, result);
            done();
        });
    });

  it('triggers whenDone when doneAddingJobs is called', function(done) {

        var queue = new capisce.WorkingQueue(1);
        var waited = 0;

        queue.whenDone(function() {
            assert.equal(1, waited);
            done();
        });

        setTimeout(function() {
            waited = 1;
            queue.doneAddingJobs();
        }, LAPSE);
  });

  it('does not trigger whenDone twice when doneAddingJobs is called after adding a job', function(done) {

        var queue = new capisce.WorkingQueue(1);
        var waited = 0;

        queue.perform(function(over) {
            waited = 1;
            over();
        });

        queue.whenDone(function() {
            assert.equal(1, waited);
            setTimeout(function() {
                done();
            }, 2*LAPSE);
        });

        setTimeout(function() {
            waited = 2;
            queue.doneAddingJobs();
        }, LAPSE);
  });

  it('holds when asked to', function(done) {

        var queue = new capisce.WorkingQueue(1);
        var result = 0;
        var isDone = 0;

        queue.hold();
        queue.perform(function(over) {
            result = 1;
            over();
        });

        setTimeout(function() {
            assert.equal(0, result);

            queue.go();

            setTimeout(function() {
                assert.equal(1, result);
                assert.equal(1, isDone);
                done();
            }, LAPSE);
        }, LAPSE);

        queue.whenDone(function() {
            assert.equal(1, result);
            assert.equal(0, isDone);
            isDone = 1;
        });
  });

  it('runs jobs in sequence when concurrency==1', function(done) {

        var start = new Date().getTime();
        var result = 0;
        var repeat = 8;
        var queue = new capisce.WorkingQueue(1);

        function job(over) {
            setTimeout(function() {
                result++;
                over();
            }, LAPSE);
        }

        for(var i=0; i<repeat; i++) {
            queue.perform(job);
        }

        queue.whenDone(function() {
            var end = new Date().getTime();
            assert.equal(repeat, result);
            assert.ok(end - start >= repeat * LAPSE, "jobs are not serialized");
            done();
        });

  });

  it('runs jobs in parallel when concurrency>1', function(done) {

        var start = new Date().getTime();
        var result = 0;
        var repeat = 8;
        var queue = new capisce.WorkingQueue(2);

        function job(over) {
            setTimeout(function() {
                result++;
                over();
            }, LAPSE);
        }

        for(var i=0; i<repeat; i++) {
            queue.perform(job);
        }

        queue.whenDone(function() {
            var end = new Date().getTime();
            assert.equal(repeat, result);
            assert.ok(end - start > repeat * LAPSE / 2, "concurrency level is not respected");
            assert.ok(end - start < repeat * LAPSE, "jobs should not be serialized");
            done();
        });

  });

  it('can be built with sequence()', function(done) {
        var result = 0;

        capisce.sequence().perform(function(over) {
            result += 2;
            over();
            assert.equal(2, result);
        }).then(function(over) {
            result += 3;
            over();
            assert.equal(5, result);
        }).whenDone(function() {
            assert.equal(5, result);
            done();
        });
  });

  it('can be built with sequence(), using the shortcut notation', function(done) {
        var result = 0;

        capisce.sequence(function(over) {
            result += 2;
            over();
            assert.equal(2, result);
        }).then(function(over) {
            result += 3;
            over();
            assert.equal(5, result);
        }).whenDone(function() {
            assert.equal(5, result);
            done();
        });
  });

  it('can be built with sequence(), using the shortcut notation and job parameters', function(done) {
        var result = 0;

        capisce.sequence(function(i, over) {
            result += i;
            over();
            assert.equal(i, result);
        }, 5).then(function(over) {
            setTimeout(function() {
                result += 3;
                over();
                assert.equal(8, result);
            }, LAPSE);
        }).whenDone(function() {
            assert.equal(8, result);
            done();
        });
  });

  it('supports enqueuing jobs with other.then', function(done) {
        var result = 0;

        capisce.sequence().perform(function(over) {
            result += 2;
            over.then(function(over) {
                result += 3;
                over();
            });
            assert.equal(2, result);
        }).whenDone(function() {
            assert.equal(5, result);
            done();
        });
  });

});

describe('ConcurrentWorkingQueue', function(){

    it('collects results', function(done) {
        var queue = new capisce.CollectingWorkingQueue(2);
        var repeat = 10;

        function job(i) {
            return function(over) {
                setTimeout(function() {
                    over(null, i*7);
                }, Math.random() * 100);
            };
        }

        for(var i=0; i<repeat; i++) {
            queue.perform(job(i));
        }

        queue.whenDone(function(result) {
            assert.equal(repeat, result.length);
            result.sort();
            assert.equal(0, result[0][2]);
            assert.equal((repeat-1)*7, result[repeat-1][2]);
            done();
        });

    });

    it('collects results when passed parameters', function(done) {
        var queue = new capisce.CollectingWorkingQueue(2);
        var repeat = 10;

        function job(i, j, over) {
            setTimeout(function() {
                over(null, i*7+j);
            }, Math.random() * 100);
        }

        for(var i=0; i<repeat; i++) {
            queue.perform(job, i, 5);
        }

        queue.whenDone(function(result) {
            assert.equal(repeat, result.length);
            result.sort();
            assert.equal(5, result[0][2]);
            assert.equal((repeat-1)*7 + 5, result[repeat-1][2]);
            done();
        });

    });
});

<commit_msg>Better tests for concurrency levels.<commit_after>"use strict";

// Make jshint happy
/*global describe:false, it:false */

var capisce = require('../lib/capisce.js');
var assert = require("assert");

var LAPSE = 50;

describe('WorkingQueue', function(){
    it('performs jobs passed without parameters', function(done){

        var queue = new capisce.WorkingQueue(1);
        var result = 0;

        queue.perform(function(over) {
            setTimeout(function() {
                result = 1;
                over();
            }, LAPSE);
        });

        queue.whenDone(function() {
            assert.equal(1, result);
            done();
        });
    });

    it('performs jobs passed with parameters', function(done){

        var queue = new capisce.WorkingQueue(1);
        var result = 0;

        queue.perform(function(a, b, over) {
            setTimeout(function() {
                result = a + b;
                over();
            }, LAPSE);
        }, 41, 1);

        queue.whenDone(function() {
            assert.equal(42, result);
            done();
        });
    });

  it('triggers whenDone when doneAddingJobs is called', function(done) {

        var queue = new capisce.WorkingQueue(1);
        var waited = 0;

        queue.whenDone(function() {
            assert.equal(1, waited);
            done();
        });

        setTimeout(function() {
            waited = 1;
            queue.doneAddingJobs();
        }, LAPSE);
  });

  it('does not trigger whenDone twice when doneAddingJobs is called after adding a job', function(done) {

        var queue = new capisce.WorkingQueue(1);
        var waited = 0;

        queue.perform(function(over) {
            waited = 1;
            over();
        });

        queue.whenDone(function() {
            assert.equal(1, waited);
            setTimeout(function() {
                done();
            }, 2*LAPSE);
        });

        setTimeout(function() {
            waited = 2;
            queue.doneAddingJobs();
        }, LAPSE);
  });

  it('holds when asked to', function(done) {

        var queue = new capisce.WorkingQueue(1);
        var result = 0;
        var isDone = 0;

        queue.hold();
        queue.perform(function(over) {
            result = 1;
            over();
        });

        setTimeout(function() {
            assert.equal(0, result);

            queue.go();

            setTimeout(function() {
                assert.equal(1, result);
                assert.equal(1, isDone);
                done();
            }, LAPSE);
        }, LAPSE);

        queue.whenDone(function() {
            assert.equal(1, result);
            assert.equal(0, isDone);
            isDone = 1;
        });
  });

  it('runs jobs in sequence when concurrency==1', function(done) {

        var start = new Date().getTime();
        var result = [];
        var repeat = 8;
        var queue = new capisce.WorkingQueue(1);
        var workers = 0;

        function job(i, over) {
            workers++;
            assert.equal(1, workers, "more than one worker in a sequence");

            setTimeout(function() {
                assert.equal(1, workers, "more than one worker in a sequence");
                result.push(i);
                workers--;
                over();
            }, Math.random() * LAPSE);
        }

        for(var i=0; i<repeat; i++) {
            queue.perform(job, i);
        }

        queue.whenDone(function() {
            var end = new Date().getTime();
            for(var i = 0; i<repeat; i++) {
                assert.equal(i, result[i], "sequence was not executed in order");
            }
            done();
        });

  });

  it('runs jobs in parallel when concurrency>1', function(done) {

        var start = new Date().getTime();
        var result = 0;
        var repeat = 8;
        var concurrency = 4;
        var queue = new capisce.WorkingQueue(concurrency);
        var workers = 0;
        var concurrent = false;

        function job(over) {
            workers++;
            assert.ok(workers<=concurrency, "concurrency level is not respected");
            if(workers > 1) {
                concurrent = true;
            }

            setTimeout(function() {
                assert.ok(workers<=concurrency, "concurrency level is not respected");
                workers--;
                result++;
                over();
            }, Math.random() * LAPSE);
        }

        for(var i=0; i<repeat; i++) {
            queue.perform(job);
        }

        queue.whenDone(function() {
            var end = new Date().getTime();
            assert.equal(repeat, result, "not all jobs have run");
            assert.ok(concurrent, "no concurrency was observed")
            done();
        });

  });

  it('can be built with sequence()', function(done) {
        var result = 0;

        capisce.sequence().perform(function(over) {
            result += 2;
            over();
            assert.equal(2, result);
        }).then(function(over) {
            result += 3;
            over();
            assert.equal(5, result);
        }).whenDone(function() {
            assert.equal(5, result);
            done();
        });
  });

  it('can be built with sequence(), using the shortcut notation', function(done) {
        var result = 0;

        capisce.sequence(function(over) {
            result += 2;
            over();
            assert.equal(2, result);
        }).then(function(over) {
            result += 3;
            over();
            assert.equal(5, result);
        }).whenDone(function() {
            assert.equal(5, result);
            done();
        });
  });

  it('can be built with sequence(), using the shortcut notation and job parameters', function(done) {
        var result = 0;

        capisce.sequence(function(i, over) {
            result += i;
            over();
            assert.equal(i, result);
        }, 5).then(function(over) {
            setTimeout(function() {
                result += 3;
                over();
                assert.equal(8, result);
            }, LAPSE);
        }).whenDone(function() {
            assert.equal(8, result);
            done();
        });
  });

  it('supports enqueuing jobs with other.then', function(done) {
        var result = 0;

        capisce.sequence().perform(function(over) {
            result += 2;
            over.then(function(over) {
                result += 3;
                over();
            });
            assert.equal(2, result);
        }).whenDone(function() {
            assert.equal(5, result);
            done();
        });
  });

});

describe('ConcurrentWorkingQueue', function(){

    it('collects results', function(done) {
        var queue = new capisce.CollectingWorkingQueue(2);
        var repeat = 10;

        function job(i) {
            return function(over) {
                setTimeout(function() {
                    over(null, i*7);
                }, Math.random() * 100);
            };
        }

        for(var i=0; i<repeat; i++) {
            queue.perform(job(i));
        }

        queue.whenDone(function(result) {
            assert.equal(repeat, result.length);
            result.sort();
            assert.equal(0, result[0][2]);
            assert.equal((repeat-1)*7, result[repeat-1][2]);
            done();
        });

    });

    it('collects results when passed parameters', function(done) {
        var queue = new capisce.CollectingWorkingQueue(2);
        var repeat = 10;

        function job(i, j, over) {
            setTimeout(function() {
                over(null, i*7+j);
            }, Math.random() * 100);
        }

        for(var i=0; i<repeat; i++) {
            queue.perform(job, i, 5);
        }

        queue.whenDone(function(result) {
            assert.equal(repeat, result.length);
            result.sort();
            assert.equal(5, result[0][2]);
            assert.equal((repeat-1)*7 + 5, result[repeat-1][2]);
            done();
        });

    });
});

<|endoftext|>


<commit_before>var test = require('tape');
var tick = require('./tick24').getInstance({fps:24});
var Sprite = require('../sprite');

test('Loading images', function(t){
	t.plan(1);
	t.timeoutAfter(2000);

	var canvas = document.createElement('canvas');
	var images = [
		'http://moves.stupid-studio.com/static/images/sprite/bjarne_01.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_02.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_03.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_04.png',
	];

	var sprite = Sprite({
		tick:tick,
		canvas: canvas
	});

	sprite
	.load(images)
	.success(function(){
		t.pass('success');
	}).error(function(){
		t.fail('error');
	});
});

test('Is playing', function(t){
	t.plan(2);
	t.timeoutAfter(2000);

	var canvas = document.createElement('canvas');
	var images = [
		'http://moves.stupid-studio.com/static/images/sprite/bjarne_01.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_02.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_03.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_04.png',
	];

	var sprite = Sprite({
		tick:tick,
		canvas: canvas
	});

	t.false(sprite.isPlaying());

	sprite
	.load(images)
	.success(function(){
		sprite.play();
		t.true(sprite.isPlaying());
	});
});

test('Is looping', function(t){
	t.plan(2);
	var count = 0;
	var canvas = document.createElement('canvas');
	var images = [
		'http://moves.stupid-studio.com/static/images/sprite/bjarne_01.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_02.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_03.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_04.png',
	];

	var sprite = Sprite({
		tick:tick,
		canvas: canvas
	});

	sprite
	.load(images)
	.success(function(){
		sprite.play();
	});

	sprite.on('ended', function(){
		t.pass();
		count++;
		if(count === 2) sprite.pause();
	});
});

test('Not looping', function(t){
	t.plan(1);
	var count = 0;
	var canvas = document.createElement('canvas');
	var images = [
		'http://moves.stupid-studio.com/static/images/sprite/bjarne_01.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_02.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_03.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_04.png',
	];

	var sprite = Sprite({
		tick:tick,
		canvas: canvas,
		loop:false
	});

	sprite
	.load(images)
	.success(function(){
		sprite.play();
	});

	sprite.on('ended', function(){
		count++;
	});

	setTimeout(function(){
		t.equal(count, 1);
	}, 2000)
});<commit_msg>small test<commit_after>var test = require('tape');
var Tick = require('stupid-tick');
var tick = Tick();
var Sprite = require('../sprite');

test('Loading images', function(t){
	t.plan(1);
	t.timeoutAfter(2000);

	var canvas = document.createElement('canvas');
	var images = [
		'http://moves.stupid-studio.com/static/images/sprite/bjarne_01.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_02.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_03.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_04.png',
	];

	var sprite = Sprite({
		tick:tick,
		canvas: canvas
	});

	sprite
	.load(images)
	.success(function(){
		t.pass('success');
	}).error(function(){
		t.fail('error');
	});
});

test('Is playing', function(t){
	t.plan(2);
	t.timeoutAfter(2000);

	var canvas = document.createElement('canvas');
	var images = [
		'http://moves.stupid-studio.com/static/images/sprite/bjarne_01.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_02.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_03.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_04.png',
	];

	var sprite = Sprite({
		tick:tick,
		canvas: canvas
	});

	t.false(sprite.isPlaying());

	sprite
	.load(images)
	.success(function(){
		sprite.play();
		t.true(sprite.isPlaying());
	});
});

test('Is looping', function(t){
	t.plan(2);
	var count = 0;
	var canvas = document.createElement('canvas');
	var images = [
		'http://moves.stupid-studio.com/static/images/sprite/bjarne_01.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_02.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_03.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_04.png',
	];

	var sprite = Sprite({
		tick:tick,
		canvas: canvas
	});

	sprite
	.load(images)
	.success(function(){
		sprite.play();
	});

	sprite.on('ended', function(){
		t.pass();
		count++;
		if(count === 2) sprite.pause();
	});
});

test('Not looping', function(t){
	t.plan(1);
	var count = 0;
	var canvas = document.createElement('canvas');
	var images = [
		'http://moves.stupid-studio.com/static/images/sprite/bjarne_01.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_02.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_03.png',
		// 'http://moves.stupid-studio.com/static/images/sprite/bjarne_04.png',
	];

	var sprite = Sprite({
		tick:tick,
		canvas: canvas,
		loop:false
	});

	sprite
	.load(images)
	.success(function(){
		sprite.play();
	});

	sprite.on('ended', function(){
		count++;
	});

	setTimeout(function(){
		t.equal(count, 1);
	}, 2000)
});<|endoftext|>


<commit_before>'use strict';
/**
 * Croppr.js unit tests
 */
var fs = require('fs');
var sinon = require('sinon');
var chai = require('chai');
var expect = chai.expect;
var assert = chai.assert;

/**
 * Create the fake html page.
 * Mock image size is 500x500.
 */
require('jsdom-global')(fs.readFileSync('test/mock.html', 'utf-8'), {
    features: {
        FetchExternalResources: ["script", "link", "img"],
        ProcessExternalResources: ["script", "img"]
    }
});
var Croppr = require('../dist/croppr.js');

describe('Croppr', function() {
    beforeEach('setup fake dom', function() {
        document.body.innerHTML = ''
    });

    describe('Croppr instantiation', function() {

        it('constructor should be a function', function() {
            assert.equal(typeof Croppr, 'function');
        });

        it('should work by passing a query selector', function() {
            assert.doesNotThrow(function() {
                new Croppr('#croppr', {});
            });
        });

        it('should work by passing an Element object', function() {
            let el = document.getElementById('croppr');
            assert.doesNotThrow(function() {
                new Croppr(el, {});
            });
        });

        it('should throw exception when element is not found', function() {
            assert.throws(function() { new Croppr('#404', {}); });
        });

        it('should throw exception when element is not an img', function() {
            document.body.innerHTML = '

';
            assert.throws(function() { new Croppr('#croppr'); });
        });

        it('should throw exception when img has no src', function() {
            document.body.innerHTML = '';
            assert.throws(function() { new Croppr('#croppr'); });
        });

        it('should work without specifying any options', function() {
            assert.doesNotThrow(function() { new Croppr('#croppr'); });
        });
    });

    describe('Croppr options', function() {
        it('should translate % values to px', function() {
            let instance = new Croppr('#croppr', {
                maxSize: [50, 50, '%']
            }, true);
            instance.cropperEl = {offsetWidth: 500, offsetHeight: 500};
            instance.options.convertToPixels({
                offsetWidth: 500,
                offsetHeight: 500
            });
            const maxSize = instance.options.maxSize;
            assert.deepEqual(maxSize, {width: 250, height: 250});
        });

        it('should have a default full sized crop region', function() {
            let instance = createMockCroppr({});
            assert.deepEqual(instance.box, {x1: 0, y1: 0, x2: 500, y2: 500});
        });

        it('should respect ratio if given', function() {
            const ratio = 1.2;
            let instance = createMockCroppr({aspectRatio: ratio});
            let boxRatio = instance.box.height()/instance.box.width();
            assert.equal(boxRatio.toFixed(2), ratio.toFixed(2));
        });

        it('should respect max size if given', function() {
            let instance = createMockCroppr({maxSize: [50, 50, 'px']});
            assert.equal(instance.box.width(), 50);
            assert.equal(instance.box.height(), 50);
        });
    });
});

describe('Croppr behaviour', function() {
    beforeEach('setup fake dom', function() {
        document.body.innerHTML = ''
    });

    describe('Respect to options', function() {
        var instance = null;
        before('setup instance and simulate movement', function() {
            instance = createMockCroppr({
                aspectRatio: 1.5,
                maxSize: [300, 300, 'px'],
                minSize: [50, 50, 'px'],
            });
        })

        afterEach('reset box', function() {
            instance.reset();
        })

        it('should respect aspect ratio on resize', function() {
            // Bottom right handle
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]}

            // Move up by 50 pixels
            simulateHandleMove(instance, handle, 500, 450);

            // Assert values
            let boxRatio = instance.box.height()/instance.box.width();
            boxRatio = boxRatio.toFixed(2);

            assert.equal(boxRatio, 1.5.toFixed(2));
        });

        it('should respect the maximum size on resize', function() {
            // Bottom right handle
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]}

            // Drag handle to bottom right
            simulateHandleMove(instance, handle, 500, 500);

            assert.isTrue(instance.box.width() <= 300);
            assert.isTrue(instance.box.height() <= 300);
        });

        it('should respect the minimum size on resize', function() {
            // Bottom right handle
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]};

            const x1 = instance.box.x1,
                  y1 = instance.box.y1;

            // Drag handle to upper left
            simulateHandleMove(instance, handle, x1 + 10, y1 + 10);

            assert.isTrue(instance.box.width() >= 50);
            assert.isTrue(instance.box.height() >= 50);
        });
    });

    describe('Handle behaviour', function() {
        var instance = null;
        before('setup instance and simulate movement', function() {
            instance = createMockCroppr({});
        });

        afterEach('reset box', function() {
            instance.reset();
        });

        it('should resize box element', function() {
            // Bottom right handle
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]};

            const x2 = instance.box.x2,
                  y2 = instance.box.y2;

            // Drag handle by -50px, -50px
            simulateHandleMove(instance, handle, x2 - 50, y2 - 50);

            assert.equal(instance.box.x2, x2 - 50);
            assert.equal(instance.box.y2, y2 - 50);
        });

        it('should work when handle is flipped', function() {
            // Right and left handles
            const handleR = {constraints: [0, 1, 0, 0], position: [1, 0.5]};
            const handleL = {constraints: [0, 0, 0, 1], position: [0, 0.5]};

            // Drag right handle to center then left handle to right boundary
            simulateHandleMove(instance, handleR, 250, 250);
            simulateHandleMove(instance, handleL, 500, 250);

            assert.isTrue(instance.box.x2 > instance.box.x1);
            assert.isTrue(instance.box.y2 > instance.box.y1);
        });

        it('should constrain within the boundaries', function() {
            // Right handle
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]};

            // Drag handle beyond boundaries
            const x2 = instance.cropperEl.offsetWidth + 100;
            const y2 = instance.cropperEl.offsetHeight + 100;
            simulateHandleMove(instance, handle, x2, y2);

            assert.isTrue(instance.box.x2 <= instance.cropperEl.offsetWidth);
            assert.isTrue(instance.box.y2 <= instance.cropperEl.offsetHeight);
        });
    });

    describe('Moving behaviour', function() {
        var instance = null;
        before('setup instance and simulate movement', function() {
            instance = createMockCroppr({});
        });

        afterEach('reset box', function() {
            instance.reset();
        });

        it('should move box element', function() {
            instance.resizeTo(250, 250);
            instance.moveTo(0, 0);
            simulateRegionMove(instance, 0, 0, 250, 250);

            assert.equal(instance.box.x1, 250);
            assert.equal(instance.box.y1, 250);
            assert.equal(instance.box.x2, 500);
            assert.equal(instance.box.y2, 500);
        });

        it('should constrain within the boundary', function() {
            instance.resizeTo(250, 250);
            instance.moveTo(0, 0);
            simulateRegionMove(instance, 0, 0, 500, 500);

            assert.equal(instance.box.x1, 250);
            assert.equal(instance.box.y1, 250);
            assert.equal(instance.box.x2, 500);
            assert.equal(instance.box.y2, 500);
        });
    });

    describe('Callback behaviour', function() {
        it('should call the onInitialize callback', function() {
            let instance = createMockCroppr({
                onInitialize: function() { return; }
            }, true);
            let spy = sinon.spy(instance.options, 'onInitialize');
            instance.initialize();
            assert.isTrue(spy.calledOnce);
        });

        it('should call the onUpdate callback', function() {
            let instance = createMockCroppr({
                onUpdate: function() { return; }
            });
            let spy = sinon.spy(instance.options, 'onUpdate');

            // Simulate handle resize
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]};
            simulateHandleMove(instance, handle, 250, 250);

            // Simulate region move
            simulateRegionMove(instance, 0, 0, 250, 250);

            // Simulate API methods
            instance.moveTo(0, 0);
            instance.resizeTo(50, 50);
            instance.scaleBy(2, [0, 0]);

            assert.equal(spy.callCount, 5);
        });
    });
});

/**
 * Helper functions
 */
function createMockCroppr(options, _deferred) {
    _deferred = _deferred || false;
    let instance = new Croppr('#croppr', options, true);
    sinon.stub(instance, 'createDOM', function() {
        // Mock containerEl & eventBus
        this.containerEl = document.createElement('div');
        this.containerEl['offsetWidth'] = 500;
        this.containerEl['offsetHeight'] = 500;
        this.eventBus = this.containerEl;

        // Mock imageEl
        this.imageEl = {offsetWidth: 500, offsetHeight: 500,
                        naturalWidth: 1000, naturalHeight: 1000};

        // Mock cropperEl
        this.cropperEl = {
            offsetWidth: 500,
            offsetHeight: 500,
            getBoundingClientRect: function() {
                return {left: 0, top: 0, width: 500, height: 500}
            }
        }

        // Mock clipped image el
        this.imageClippedEl = { style: {clip: null}}

        // Mock overlayEl
        this.overlayEl = document.createElement('div');

        // Mock regionEl
        this.regionEl = document.createElement('div');

        // Mock handles
        this.handles = [];
    });

    if (!_deferred) {
        instance.initialize();
    }
    return instance;
}

function simulateHandleMove(instance, handle, mouseX, mouseY) {
    // Set active handle
    const originPoint = [1 - handle.position[0], 1 - handle.position[1]];
    let originX = instance.box.getAbsolutePoint(originPoint)[0];
    let originY = instance.box.getAbsolutePoint(originPoint)[1];
    instance.activeHandle = {handle, originPoint, originX, originY}

    // Simulate movement
    instance.onHandleMoveMoving({
        detail: {mouseX: mouseX, mouseY: mouseY}
    });
}

function simulateRegionMove(instance, originX, originY, toX, toY) {
    // Set current move
    let container = instance.cropperEl.getBoundingClientRect();
    instance.currentMove = {
        offsetX: originX - instance.box.x1,
        offsetY: originY - instance.box.y1
    }

    // Simulate movement
    instance.onRegionMoveMoving({
        detail: {mouseX: toX, mouseY: toY}
    });
}<commit_msg>Update tests to cover new callbacks<commit_after>'use strict';
/**
 * Croppr.js unit tests
 */
var fs = require('fs');
var sinon = require('sinon');
var chai = require('chai');
var expect = chai.expect;
var assert = chai.assert;

/**
 * Create the fake html page.
 * Mock image size is 500x500.
 */
require('jsdom-global')(fs.readFileSync('test/mock.html', 'utf-8'), {
    features: {
        FetchExternalResources: ["script", "link", "img"],
        ProcessExternalResources: ["script", "img"]
    }
});
var Croppr = require('../dist/croppr.js');

describe('Croppr', function() {
    beforeEach('setup fake dom', function() {
        document.body.innerHTML = ''
    });

    describe('Croppr instantiation', function() {

        it('constructor should be a function', function() {
            assert.equal(typeof Croppr, 'function');
        });

        it('should work by passing a query selector', function() {
            assert.doesNotThrow(function() {
                new Croppr('#croppr', {});
            });
        });

        it('should work by passing an Element object', function() {
            let el = document.getElementById('croppr');
            assert.doesNotThrow(function() {
                new Croppr(el, {});
            });
        });

        it('should throw exception when element is not found', function() {
            assert.throws(function() { new Croppr('#404', {}); });
        });

        it('should throw exception when element is not an img', function() {
            document.body.innerHTML = '

';
            assert.throws(function() { new Croppr('#croppr'); });
        });

        it('should throw exception when img has no src', function() {
            document.body.innerHTML = '';
            assert.throws(function() { new Croppr('#croppr'); });
        });

        it('should work without specifying any options', function() {
            assert.doesNotThrow(function() { new Croppr('#croppr'); });
        });
    });

    describe('Croppr options', function() {
        it('should translate % values to px', function() {
            let instance = new Croppr('#croppr', {
                maxSize: [50, 50, '%']
            }, true);
            instance.cropperEl = {offsetWidth: 500, offsetHeight: 500};
            instance.options.convertToPixels({
                offsetWidth: 500,
                offsetHeight: 500
            });
            const maxSize = instance.options.maxSize;
            assert.deepEqual(maxSize, {width: 250, height: 250});
        });

        it('should have a default full sized crop region', function() {
            let instance = createMockCroppr({});
            assert.deepEqual(instance.box, {x1: 0, y1: 0, x2: 500, y2: 500});
        });

        it('should respect ratio if given', function() {
            const ratio = 1.2;
            let instance = createMockCroppr({aspectRatio: ratio});
            let boxRatio = instance.box.height()/instance.box.width();
            assert.equal(boxRatio.toFixed(2), ratio.toFixed(2));
        });

        it('should respect max size if given', function() {
            let instance = createMockCroppr({maxSize: [50, 50, 'px']});
            assert.equal(instance.box.width(), 50);
            assert.equal(instance.box.height(), 50);
        });
    });
});

describe('Croppr behaviour', function() {
    beforeEach('setup fake dom', function() {
        document.body.innerHTML = ''
    });

    describe('Respect to options', function() {
        var instance = null;
        before('setup instance and simulate movement', function() {
            instance = createMockCroppr({
                aspectRatio: 1.5,
                maxSize: [300, 300, 'px'],
                minSize: [50, 50, 'px'],
            });
        })

        afterEach('reset box', function() {
            instance.reset();
        })

        it('should respect aspect ratio on resize', function() {
            // Bottom right handle
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]}

            // Move up by 50 pixels
            simulateHandleMove(instance, handle, 500, 450);

            // Assert values
            let boxRatio = instance.box.height()/instance.box.width();
            boxRatio = boxRatio.toFixed(2);

            assert.equal(boxRatio, 1.5.toFixed(2));
        });

        it('should respect the maximum size on resize', function() {
            // Bottom right handle
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]}

            // Drag handle to bottom right
            simulateHandleMove(instance, handle, 500, 500);

            assert.isTrue(instance.box.width() <= 300);
            assert.isTrue(instance.box.height() <= 300);
        });

        it('should respect the minimum size on resize', function() {
            // Bottom right handle
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]};

            const x1 = instance.box.x1,
                  y1 = instance.box.y1;

            // Drag handle to upper left
            simulateHandleMove(instance, handle, x1 + 10, y1 + 10);

            assert.isTrue(instance.box.width() >= 50);
            assert.isTrue(instance.box.height() >= 50);
        });
    });

    describe('Handle behaviour', function() {
        var instance = null;
        before('setup instance and simulate movement', function() {
            instance = createMockCroppr({});
        });

        afterEach('reset box', function() {
            instance.reset();
        });

        it('should resize box element', function() {
            // Bottom right handle
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]};

            const x2 = instance.box.x2,
                  y2 = instance.box.y2;

            // Drag handle by -50px, -50px
            simulateHandleMove(instance, handle, x2 - 50, y2 - 50);

            assert.equal(instance.box.x2, x2 - 50);
            assert.equal(instance.box.y2, y2 - 50);
        });

        it('should work when handle is flipped', function() {
            // Right and left handles
            const handleR = {constraints: [0, 1, 0, 0], position: [1, 0.5]};
            const handleL = {constraints: [0, 0, 0, 1], position: [0, 0.5]};

            // Drag right handle to center then left handle to right boundary
            simulateHandleMove(instance, handleR, 250, 250);
            simulateHandleMove(instance, handleL, 500, 250);

            assert.isTrue(instance.box.x2 > instance.box.x1);
            assert.isTrue(instance.box.y2 > instance.box.y1);
        });

        it('should constrain within the boundaries', function() {
            // Right handle
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]};

            // Drag handle beyond boundaries
            const x2 = instance.cropperEl.offsetWidth + 100;
            const y2 = instance.cropperEl.offsetHeight + 100;
            simulateHandleMove(instance, handle, x2, y2);

            assert.isTrue(instance.box.x2 <= instance.cropperEl.offsetWidth);
            assert.isTrue(instance.box.y2 <= instance.cropperEl.offsetHeight);
        });
    });

    describe('Moving behaviour', function() {
        var instance = null;
        before('setup instance and simulate movement', function() {
            instance = createMockCroppr({});
        });

        afterEach('reset box', function() {
            instance.reset();
        });

        it('should move box element', function() {
            instance.resizeTo(250, 250);
            instance.moveTo(0, 0);
            simulateRegionMove(instance, 0, 0, 250, 250);

            assert.equal(instance.box.x1, 250);
            assert.equal(instance.box.y1, 250);
            assert.equal(instance.box.x2, 500);
            assert.equal(instance.box.y2, 500);
        });

        it('should constrain within the boundary', function() {
            instance.resizeTo(250, 250);
            instance.moveTo(0, 0);
            simulateRegionMove(instance, 0, 0, 500, 500);

            assert.equal(instance.box.x1, 250);
            assert.equal(instance.box.y1, 250);
            assert.equal(instance.box.x2, 500);
            assert.equal(instance.box.y2, 500);
        });
    });

    describe('Callback behaviour', function() {
        it('should call the onInitialize callback', function() {
            let instance = createMockCroppr({
                onInitialize: function() { return; }
            }, true);
            let spy = sinon.spy(instance.options, 'onInitialize');
            instance.initialize();
            assert.isTrue(spy.calledOnce);
        });

        it('should trigger all onCrop callbacks via moving handles', function() {
            let instance = createMockCroppr({
                onCropStart: function() { return; },
                onCropMove: function() { return; },
                onCropEnd: function() { return; }
            });
            let onCropStartSpy = sinon.spy(instance.options, 'onCropStart');
            let onCropMoveSpy = sinon.spy(instance.options, 'onCropMove');
            let onCropEndSpy = sinon.spy(instance.options, 'onCropEnd');

            // Simulate handle resize
            const handle = {constraints: [0, 1, 1, 0], position: [1, 1]};
            simulateHandleMove(instance, handle, 250, 250);

            assert.isTrue(onCropStartSpy.called && onCropMoveSpy.called && onCropEndSpy.called);
        });

        it('should trigger all onCrop callbacks via moving region', function() {
            let instance = createMockCroppr({
                onCropStart: function() { return; },
                onCropMove: function() { return; },
                onCropEnd: function() { return; }
            });
            let onCropStartSpy = sinon.spy(instance.options, 'onCropStart');
            let onCropMoveSpy = sinon.spy(instance.options, 'onCropMove');
            let onCropEndSpy = sinon.spy(instance.options, 'onCropEnd');

            // Simulate region move
            simulateRegionMove(instance, 0, 0, 250, 250);

            assert.isTrue(onCropStartSpy.called && onCropMoveSpy.called && onCropEndSpy.called);
        });
    });
});

/**
 * Helper functions
 */
function createMockCroppr(options, _deferred) {
    _deferred = _deferred || false;
    let instance = new Croppr('#croppr', options, true);
    sinon.stub(instance, 'createDOM', function() {
        // Mock containerEl & eventBus
        this.containerEl = document.createElement('div');
        this.containerEl['offsetWidth'] = 500;
        this.containerEl['offsetHeight'] = 500;
        this.eventBus = this.containerEl;

        // Mock imageEl
        this.imageEl = {offsetWidth: 500, offsetHeight: 500,
                        naturalWidth: 1000, naturalHeight: 1000};

        // Mock cropperEl
        this.cropperEl = {
            offsetWidth: 500,
            offsetHeight: 500,
            getBoundingClientRect: function() {
                return {left: 0, top: 0, width: 500, height: 500}
            }
        }

        // Mock clipped image el
        this.imageClippedEl = { style: {clip: null}}

        // Mock overlayEl
        this.overlayEl = document.createElement('div');

        // Mock regionEl
        this.regionEl = document.createElement('div');

        // Mock handles
        this.handles = [];
    });

    if (!_deferred) {
        instance.initialize();
    }
    return instance;
}

function simulateHandleMove(instance, handle, mouseX, mouseY) {
    // Simulate handle start
    instance.eventBus.dispatchEvent(new CustomEvent('handlestart', {
        detail: { handle: handle }
    }));

    // Simulate handle move
    instance.eventBus.dispatchEvent(new CustomEvent('handlemove', {
        detail: {mouseX: mouseX, mouseY: mouseY}
    }));

    // Simulate handle end
    instance.eventBus.dispatchEvent(new CustomEvent('handleend', {
        detail: {mouseX: mouseX, mouseY: mouseY}
    }));
}

function simulateRegionMove(instance, originX, originY, toX, toY) {
    // Simulate region movement start
    instance.eventBus.dispatchEvent(new CustomEvent('regionstart', {
        detail: { mouseX: originX, mouseY: originY }
    }));

    // Simulate region movement
    instance.eventBus.dispatchEvent(new CustomEvent('regionmove', {
        detail: { mouseX: toX, mouseY: toY }
    }));

    // Simulate region movement end
    instance.eventBus.dispatchEvent(new CustomEvent('regionend', {
        detail: { mouseX: toX, mouseY: toY }
    }));
}<|endoftext|>


<commit_before>/*eslint-env browser */
/* jshint browser: true, esnext: true */

/**
* Does this UA's primary pointer support true hovering
* OR does the UA at least not try to quirkily emulate hovering,
* such that :hover CSS styles are appropriate?
* Essentially tries to shim the `@media (hover: hover)` CSS media query feature.
* @type {boolean}
*/
export function supportsTrueHover() {
    if (!window.matchMedia) {
        // Ancient non-IE, or IE<=9, per http://caniuse.com/#feat=matchmedia
        var ua = navigator.userAgent;
        var isIE9mobileInMobileMode = ua.indexOf('MSIE 9.0') > -1 && (ua.indexOf('XBLWP7') > -1 || ua.indexOf('ZuneWP7') > -1);
        if (isIE9mobileInMobileMode) {
            // FIXME: IE9 Mobile in Mobile mode; force hoverEnabled to false???
            return false;
        }
        // UA is ancient enough to probably be a desktop computer or at least not attempt emulation of hover.
        return true;
    }

    // CSSWG Media Queries Level 4 draft
    //     http://drafts.csswg.org/mediaqueries/#hover
    if (window.matchMedia(
            '(hover: none),(-moz-hover: none),(-ms-hover: none),(-webkit-hover: none),' +
            '(hover: on-demand),(-moz-hover: on-demand),(-ms-hover: on-demand),(-webkit-hover: on-demand)'
    ).matches) {
        // true hovering explicitly not supported by primary pointer
        return false;
    }
    if (window.matchMedia('(hover: hover),(-moz-hover: hover),(-ms-hover: hover),(-webkit-hover: hover)').matches) {
        // true hovering explicitly supported by primary pointer
        return true;
    }
    // `hover` media feature not implemented by this browser; keep probing

    // Touch generally implies that hovering is merely emulated,
    // which doesn't count as true hovering support for our purposes
    // due to the quirkiness of the emulation (e.g. :hover being sticky).

    // W3C Pointer Events LC WD, 13 November 2014
    //     http://www.w3.org/TR/2014/WD-pointerevents-20141113/
    // Prefixed in IE10, per http://caniuse.com/#feat=pointer
    var supportsPointerEvents = window.PointerEvent || window.MSPointerEvent;
    if (supportsPointerEvents) {
        var pointerEventsIsTouch = (window.navigator.maxTouchPoints || window.navigator.msMaxTouchPoints) > 0;
        return !pointerEventsIsTouch;
    }

    // Mozilla's -moz-touch-enabled
    //     https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#-moz-touch-enabled
    if (window.matchMedia('(touch-enabled),(-moz-touch-enabled),(-ms-touch-enabled),(-webkit-touch-enabled)').matches) {
        return false;
    }

    // W3C Touch Events
    //     http://www.w3.org/TR/2013/REC-touch-events-20131010/
    if ('ontouchstart' in window) {
        return false;
    }

    // OPEN ISSUE: Should we look for IE's "Touch" userAgent token?

    // UA's pointer is non-touch and thus likely either supports true hovering or at least does not try to emulate it.
    return true;
}
<commit_msg>sniffing for IE's "Touch" UA token seems unnecessary<commit_after>/*eslint-env browser */
/* jshint browser: true, esnext: true */

/**
* Does this UA's primary pointer support true hovering
* OR does the UA at least not try to quirkily emulate hovering,
* such that :hover CSS styles are appropriate?
* Essentially tries to shim the `@media (hover: hover)` CSS media query feature.
* @type {boolean}
*/
export function supportsTrueHover() {
    if (!window.matchMedia) {
        // Ancient non-IE, or IE<=9, per http://caniuse.com/#feat=matchmedia
        var ua = navigator.userAgent;
        var isIE9mobileInMobileMode = ua.indexOf('MSIE 9.0') > -1 && (ua.indexOf('XBLWP7') > -1 || ua.indexOf('ZuneWP7') > -1);
        if (isIE9mobileInMobileMode) {
            // FIXME: IE9 Mobile in Mobile mode; force hoverEnabled to false???
            return false;
        }
        // UA is ancient enough to probably be a desktop computer or at least not attempt emulation of hover.
        return true;
    }

    // CSSWG Media Queries Level 4 draft
    //     http://drafts.csswg.org/mediaqueries/#hover
    if (window.matchMedia(
            '(hover: none),(-moz-hover: none),(-ms-hover: none),(-webkit-hover: none),' +
            '(hover: on-demand),(-moz-hover: on-demand),(-ms-hover: on-demand),(-webkit-hover: on-demand)'
    ).matches) {
        // true hovering explicitly not supported by primary pointer
        return false;
    }
    if (window.matchMedia('(hover: hover),(-moz-hover: hover),(-ms-hover: hover),(-webkit-hover: hover)').matches) {
        // true hovering explicitly supported by primary pointer
        return true;
    }
    // `hover` media feature not implemented by this browser; keep probing

    // Touch generally implies that hovering is merely emulated,
    // which doesn't count as true hovering support for our purposes
    // due to the quirkiness of the emulation (e.g. :hover being sticky).

    // W3C Pointer Events LC WD, 13 November 2014
    //     http://www.w3.org/TR/2014/WD-pointerevents-20141113/
    // Prefixed in IE10, per http://caniuse.com/#feat=pointer
    var supportsPointerEvents = window.PointerEvent || window.MSPointerEvent;
    if (supportsPointerEvents) {
        var pointerEventsIsTouch = (window.navigator.maxTouchPoints || window.navigator.msMaxTouchPoints) > 0;
        return !pointerEventsIsTouch;
    }

    // Mozilla's -moz-touch-enabled
    //     https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#-moz-touch-enabled
    if (window.matchMedia('(touch-enabled),(-moz-touch-enabled),(-ms-touch-enabled),(-webkit-touch-enabled)').matches) {
        return false;
    }

    // W3C Touch Events
    //     http://www.w3.org/TR/2013/REC-touch-events-20131010/
    if ('ontouchstart' in window) {
        return false;
    }

    // UA's pointer is non-touch and thus likely either supports true hovering or at least does not try to emulate it.
    return true;
}
<|endoftext|>


<commit_before>// Copyright (c) 2017 Intel Corporation. All rights reserved.
// Use of this source code is governed by an Apache 2.0 license
// that can be found in the LICENSE file.

'use strict';

/* global describe, it, before, after */
const assert = require('assert');
let rs2;
try {
  rs2 = require('node-librealsense');
} catch (e) {
  rs2 = require('../index.js');
}

let config;
let pipeline;
let serial;
describe('Config test', function() {
  before(function() {
    pipeline = new rs2.Pipeline();
    config = new rs2.Config();
    const ctx = new rs2.Context();
    const devices = ctx.queryDevices().devices;
    assert(devices.length > 0); // Device must be connected
    const dev = devices[0];
    serial = dev.getCameraInfo(rs2.camera_info.CAMERA_INFO_SERIAL_NUMBER);
  });

  after(function() {
    pipeline.destroy();
    rs2.cleanup();
  });

  it('Testing method canResolve - 0 argument', () => {
    assert.throws(() => {
      config.canResolve();
    });
  });

  it('Testing method canResolve - 2 argument', () => {
    assert.throws(() => {
      config.canResolve(pipeline, pipeline);
    });
  });

  it('Testing method canResolve - invalid argument', () => {
    assert.throws(() => {
      config.canResolve('dummy');
    });
  });

  it('Testing method canResolve - valid argument', () => {
    let rtn;
    assert.doesNotThrow(() => {
      rtn = config.canResolve(pipeline);
    });
    assert.equal(typeof rtn, 'boolean');
  });

  it('Testing method disableAllStreams - 0 argument', () => {
    assert.doesNotThrow(() => {
      config.disableAllStreams();
    });
  });

  it('Testing method disableAllStreams - 1 argument', () => {
    assert.doesNotThrow(() => {
      config.disableAllStreams(1);
    });
  });

  it('Testing method disableStream - 0 argument', () => {
    assert.throws(() => {
      config.disableStream();
    });
  });

  it('Testing method disableStream - invalid argument', () => {
    assert.throws(() => {
      config.disableStream('dummy');
    });
  });

  it('Testing method disableStream - valid argument', () => {
    for (let i in rs2.stream) {
      if (rs2.stream[i] &&
        i.toUpperCase() !== 'STREAM_COUNT' && // skip counter
        i !== 'streamToString' // skip method
      ) {
        assert.doesNotThrow(() => { // jshint ignore:line
          config.disableStream(rs2.stream[i]);
        });
      }
    }
  });

  it('Testing method enableDevice - 0 argument', () => {
    assert.throws(() => {
      config.enableDevice();
    });
  });

  it('Testing method enableDevice - invalid argument', () => {
    assert.doesNotThrow(() => {
      config.enableDevice('dummy');
    });
  });

  it('Testing method enableDevice - valid argument', () => {
    assert.doesNotThrow(() => {
      config.enableDevice(serial);
    });
  });

  it('Testing method enableStream - 0 argument', () => {
    assert.throws(() => {
      config.enableStream();
    });
  });

  it('Testing method enableStream - invalid argument', () => {
    assert.throws(() => {
      config.enableStream('dummy', 1, 1, 1, 1, 1);
    });
  });

  it('Testing method enableStream - valid argument', () => {
    // eslint-disable-next-line guard-for-in
    for (let i in rs2.stream) {
      for (let j in rs2.format) {
        if (rs2.stream[i] &&
          i.toUpperCase() !== 'STREAM_COUNT' && // skip counter
          i !== 'streamToString' && // skip method
          rs2.format[j] &&
          j.toUpperCase() !== 'FORMAT_COUNT' && // skip counter
          j !== 'formatToString' // skip method
        ) {
          assert.doesNotThrow(() => { // jshint ignore:line
            config.enableStream(rs2.stream[i], 1, 1, 1, rs2.format[j], 1);
          });
        }
      }
    }
  });

  it('Testing method resolve - 0 argument', () => {
    assert.throws(() => {
      config.resolve();
    });
  });

  it('Testing method resolve - invalid argument', () => {
    assert.throws(() => {
      config.resolve('dummy');
    });
  });

  it('Testing method resolve - valid argument', () => {
    let pp;
    assert.doesNotThrow(() => {
      pp = config.resolve(pipeline);
    });
    assert(pp instanceof rs2.PipelineProfile);
  });

  it('Testing method enableAllStreams - 0 argument', () => {
    assert.doesNotThrow(() => {
      config.enableAllStreams();
    });
  });

  it('Testing method enableAllStreams - 1 argument', () => {
    assert.doesNotThrow(() => {
      config.enableAllStreams(1);
    });
  });
});
<commit_msg>[nodejs] Add test cases for config test.<commit_after>// Copyright (c) 2017 Intel Corporation. All rights reserved.
// Use of this source code is governed by an Apache 2.0 license
// that can be found in the LICENSE file.

'use strict';

/* global describe, it, beforeEach, afterEach */
const assert = require('assert');
const fs = require('fs');
let rs2;
try {
  rs2 = require('node-librealsense');
} catch (e) {
  rs2 = require('../index.js');
}

let fileName = 'record.bag';
let config;
let pipeline;
let serial;
describe('Config test', function() {
  beforeEach(function() {
    pipeline = new rs2.Pipeline();
    config = new rs2.Config();
    const ctx = new rs2.Context();
    const devices = ctx.queryDevices().devices;
    assert(devices.length > 0); // Device must be connected
    const dev = devices[0];
    serial = dev.getCameraInfo(rs2.camera_info.CAMERA_INFO_SERIAL_NUMBER);
  });

  afterEach(function() {
    pipeline.destroy();
    rs2.cleanup();
    if (fs.existsSync(fileName)) {
      fs.unlinkSync(fileName);
    }
  });

  function createRrdFile() {
    const ctx = new rs2.Context();
    let dev = ctx.queryDevices().devices[0];
    // record to file record.bag
    let recorder = new rs2.RecorderDevice(fileName, dev);
    let sensors = recorder.querySensors();
    let sensor = sensors[0];
    let profiles = sensor.getStreamProfiles();
    for (let i =0; i < profiles.length; i++) {
      if (profiles[i].streamType === rs2.stream.STREAM_DEPTH &&
          profiles[i].fps === 30 &&
          profiles[i].width === 640 &&
          profiles[i].height === 480 &&
          profiles[i].format === rs2.format.FORMAT_Z16) {
        sensor.open(profiles[i]);
      }
    }
    // record 10 frames
    let cnt = 0;
    sensor.start((frame) => {
      cnt++;
      if (cnt === 10) {
        // stop recording
        recorder.reset();
        rs2.cleanup();
      }
    });
  }

  it('Testing method canResolve - 0 argument', () => {
    assert.throws(() => {
      config.canResolve();
    });
  });

  it('Testing method canResolve - 2 argument', () => {
    assert.throws(() => {
      config.canResolve(pipeline, pipeline);
    });
  });

  it('Testing method canResolve - invalid argument', () => {
    assert.throws(() => {
      config.canResolve('dummy');
    });
  });

  it('Testing method canResolve - valid argument', () => {
    let rtn;
    assert.doesNotThrow(() => {
      rtn = config.canResolve(pipeline);
    });
    assert.equal(typeof rtn, 'boolean');
  });

  it('Testing method disableAllStreams - 0 argument', () => {
    assert.doesNotThrow(() => {
      config.disableAllStreams();
    });
  });

  it('Testing method disableAllStreams - 1 argument', () => {
    assert.doesNotThrow(() => {
      config.disableAllStreams(1);
    });
  });

  it('Testing method disableStream - 0 argument', () => {
    assert.throws(() => {
      config.disableStream();
    });
  });

  it('Testing method disableStream - invalid argument', () => {
    assert.throws(() => {
      config.disableStream('dummy');
    });
  });

  it('Testing method disableStream - valid argument', () => {
    for (let i in rs2.stream) {
      if (rs2.stream[i] &&
        i.toUpperCase() !== 'STREAM_COUNT' && // skip counter
        i !== 'streamToString' // skip method
      ) {
        assert.doesNotThrow(() => { // jshint ignore:line
          config.disableStream(rs2.stream[i]);
        });
      }
    }
  });

  it('Testing method enableDevice - 0 argument', () => {
    assert.throws(() => {
      config.enableDevice();
    });
  });

  it('Testing method enableDevice - invalid argument', () => {
    assert.doesNotThrow(() => {
      config.enableDevice('dummy');
    });
  });

  it('Testing method enableDevice - valid argument', () => {
    assert.doesNotThrow(() => {
      config.enableDevice(serial);
    });
  });

  it('Testing method enableStream - 0 argument', () => {
    assert.throws(() => {
      config.enableStream();
    });
  });

  it('Testing method enableStream - invalid argument', () => {
    assert.throws(() => {
      config.enableStream('dummy', 1, 1, 1, 1, 1);
    });
  });

  it('Testing method enableStream - valid argument', () => {
    // eslint-disable-next-line guard-for-in
    for (let i in rs2.stream) {
      for (let j in rs2.format) {
        if (rs2.stream[i] &&
          i.toUpperCase() !== 'STREAM_COUNT' && // skip counter
          i !== 'streamToString' && // skip method
          rs2.format[j] &&
          j.toUpperCase() !== 'FORMAT_COUNT' && // skip counter
          j !== 'formatToString' // skip method
        ) {
          assert.doesNotThrow(() => { // jshint ignore:line
            config.enableStream(rs2.stream[i], 1, 1, 1, rs2.format[j], 1);
          });
        }
      }
    }
  });

  it('Testing method resolve - 0 argument', () => {
    assert.throws(() => {
      config.resolve();
    });
  });

  it('Testing method resolve - invalid argument', () => {
    assert.throws(() => {
      config.resolve('dummy');
    });
  });

  it('Testing method resolve - valid argument', () => {
    let pp;
    assert.doesNotThrow(() => {
      pp = config.resolve(pipeline);
    });
    assert(pp instanceof rs2.PipelineProfile);
  });

  it('Testing method enableAllStreams - 0 argument', () => {
    assert.doesNotThrow(() => {
      config.enableAllStreams();
    });
  });

  it('Testing method enableAllStreams - 1 argument', () => {
    assert.doesNotThrow(() => {
      config.enableAllStreams(1);
    });
  });

  it('Testing method enableDeviceFromFile - 0 argument', () => {
    assert.throws(() => {
      config.enableDeviceFromFile();
    });
  });

  it('Testing method enableDeviceFromFile - 2 argument', () => {
    assert.throws(() => {
      config.enableDeviceFromFile(1, 1);
    });
  });

  it('Testing method enableDeviceFromFile - argument with number', () => {
    assert.throws(() => {
      config.enableDeviceFromFile(1);
    });
  });

  it('Testing method enableDeviceFromFile - with file', () => {
    createRrdFile();
    assert.doesNotThrow(() => {
      config.enableDeviceFromFile(fileName);
    });
  });

  it('Testing method enableDeviceFromFile - with invalid argument', () => {
    assert.throws(() => {
      config.enableDeviceFromFile('dummy');
    });
  });

  it('Testing method enableDeviceFromFile - after enableRecordToFile', () => {
    assert.doesNotThrow(() => {
      config.enableRecordToFile(fileName);
      pipeline.start(config);
    });
    assert.throws(() => {
      config.enableDeviceFromFile(fileName);
    });
  });

  it('Testing method enableRecordToFile - 0 argument', () => {
    assert.throws(() => {
      config.enableRecordToFile();
    });
  });

  it('Testing method enableRecordToFile - two arguments', () => {
    assert.throws(() => {
      config.enableRecordToFile(fileName, fileName);
    });
  });

  it('Testing method enableRecordToFile - argument with number', () => {
    assert.throws(() => {
      config.enableRecordToFile(1);
    });
  });

  it('Testing method enableRecordToFile - without pipeline.start', () => {
    assert.doesNotThrow(() => {
      config.enableRecordToFile(fileName);
    });
    assert.equal(fs.existsSync(fileName), false);
  });

  it('Testing method enableRecordToFile - value result', () => {
    assert.doesNotThrow(() => {
      config.enableRecordToFile(fileName);
      pipeline.start(config);
    });
    assert.equal(fs.existsSync(fileName), true);
    assert.doesNotThrow(() => {
      let frameSet = pipeline.waitForFrames();
      assert(frameSet instanceof rs2.VideoFrame)
    });
  });

  it('Testing method enableRecordToFile - then enableDeviceFromFile', () => {
    assert.doesNotThrow(() => {
      config.enableRecordToFile(fileName);
      pipeline.start(config);
      let frameSet = pipeline.waitForFrames();
      assert(frameSet instanceof rs2.VideoFrame)
    });
    assert.equal(fs.existsSync(fileName), true);
    assert.throws(() => {
      config.enableDeviceFromFile(fileName);
    });
  });

  it('Testing method enableRecordToFile - fileName has been exist', () => {
    fs.closeSync(fs.openSync(fileName, 'w'));
    assert.doesNotThrow(() => {
      config.enableRecordToFile(fileName);
      pipeline.start(config);
    });
    assert.doesNotThrow(() => {
      let frameSet = pipeline.waitForFrames();
      assert(frameSet instanceof rs2.VideoFrame)
    });
    assert.equal(fs.existsSync(fileName), true);
  });
});
<|endoftext|>


<commit_before>var helper = require('./helper');
var assert = require('assert');

describe('generate different types of data', function() {
  var res = { item: null };
  before(function(done) {
    var opts = {
      size: 1,
      schema: {
        double: {
          zero: '{{Double(0)}}',
          one: '{{Double(1)}}',
          decimal: '{{Double(0.1)}}',
          neg: '{{Double(-0.1)}}'
        },
        boolean: {
          basic: '{{Boolean(true)}}',
          interp: '{{Boolean(0)}}',
          string: '{{Boolean("false")}}'
        },
        date: {
          basic: '{{Date(0)}}',
          string: '{{Date("01/01/2000")}}',
          type: '{{Date(chance.date())}}'
        }
      }
    };
    helper.getResults(opts, function (err, items) {
      if (err) return done(err);
      res.item = items[0];
      done();
    });
  });

  describe('#double', function() {
    it('should support integer', function () {
      assert.ok(typeof res.item.double.zero === 'number');
      assert.strictEqual(0, res.item.double.zero);
      assert.ok(typeof res.item.double.one === 'number');
      assert.strictEqual(1, res.item.double.one);
    });

    it('should support decimal', function () {
      assert.ok(typeof res.item.double.decimal === 'number');
      assert.strictEqual(0.1, res.item.double.decimal);
    });

    it('should support negatives', function () {
      assert.ok(typeof res.item.double.neg === 'number');
      assert.strictEqual(-0.1, res.item.double.neg);
    });
  });

  describe('#boolean', function() {
    it('should be able to build from boolean', function () {
      assert.ok(typeof res.item.boolean.basic === 'boolean');
      assert.strictEqual(true, res.item.boolean.basic);
    });

    it('should be able to interpolate from other values', function () {
      assert.ok(typeof res.item.boolean.interp === 'boolean');
      assert.strictEqual(false, res.item.boolean.interp);
      assert.ok(typeof res.item.boolean.string === 'boolean');
      assert.strictEqual(true, res.item.boolean.string);
    });
  });

  describe('#date', function() {
    it('should be able to build from integer', function () {
      assert.ok(res.item.date.basic instanceof Date);
      assert.strictEqual(0, res.item.date.basic.valueOf());
    });

    it('should be able to build from string', function () {
      assert.ok(res.item.date.string instanceof Date);
      assert.strictEqual(new Date('01/01/2000').valueOf(),
        res.item.date.string.valueOf());
    });

    it('should work with chance', function () {
      assert.ok(res.item.date.type instanceof Date);
    });
  });
});
<commit_msg>added test - array of objects<commit_after>var helper = require('./helper');
var assert = require('assert');

describe('generate different types of data', function() {
  var res = { item: null };
  before(function(done) {
    var opts = {
      size: 1,
      schema: {
        double: {
          zero: '{{Double(0)}}',
          one: '{{Double(1)}}',
          decimal: '{{Double(0.1)}}',
          neg: '{{Double(-0.1)}}',
          array: ['{{Double(0)}}']
        },
        boolean: {
          basic: '{{Boolean(true)}}',
          interp: '{{Boolean(0)}}',
          string: '{{Boolean("false")}}'
        },
        date: {
          basic: '{{Date(0)}}',
          string: '{{Date("01/01/2000")}}',
          type: '{{Date(chance.date())}}'
        },
      }
    };
    helper.getResults(opts, function (err, items) {
      if (err) return done(err);
      res.item = items[0];
      done();
    });
  });

  describe('#double', function() {
    it('should support integer', function () {
      assert.ok(typeof res.item.double.zero === 'number');
      assert.strictEqual(0, res.item.double.zero);
      assert.ok(typeof res.item.double.one === 'number');
      assert.strictEqual(1, res.item.double.one);
    });

    it('should support decimal', function () {
      assert.ok(typeof res.item.double.decimal === 'number');
      assert.strictEqual(0.1, res.item.double.decimal);
    });

    it('should support negatives', function () {
      assert.ok(typeof res.item.double.neg === 'number');
      assert.strictEqual(-0.1, res.item.double.neg);
    });

    it('should work in array', function () {
      res.item.double.array.forEach(function (i) {
        assert.ok(typeof i === 'number');
        assert.strictEqual(0, i);
      });
    });
  });

  describe('#boolean', function() {
    it('should be able to build from boolean', function () {
      assert.ok(typeof res.item.boolean.basic === 'boolean');
      assert.strictEqual(true, res.item.boolean.basic);
    });

    it('should be able to interpolate from other values', function () {
      assert.ok(typeof res.item.boolean.interp === 'boolean');
      assert.strictEqual(false, res.item.boolean.interp);
      assert.ok(typeof res.item.boolean.string === 'boolean');
      assert.strictEqual(true, res.item.boolean.string);
    });
  });

  describe('#date', function() {
    it('should be able to build from integer', function () {
      assert.ok(res.item.date.basic instanceof Date);
      assert.strictEqual(0, res.item.date.basic.valueOf());
    });

    it('should be able to build from string', function () {
      assert.ok(res.item.date.string instanceof Date);
      assert.strictEqual(new Date('01/01/2000').valueOf(),
        res.item.date.string.valueOf());
    });

    it('should work with chance', function () {
      assert.ok(res.item.date.type instanceof Date);
    });
  });

});
<|endoftext|>


<commit_before>(function(mask){

	custom_Tags['define']  = Define;

	function Define(){}
	Define.prototype = {
		$meta: {
			serializeNodes: true
		},
		render: define,
		onRenderStartClient: define
	};

	function define(){
		var name;
		for(name in this.attr) break;

		var nodes = this.nodes;
		mask.registerHandler(name, Compo({
			renderStart: function(){
				this.nodes = this.nodes == null
					? nodes
					: mask.merge(nodes, this.nodes, this)
					;
			}
		}));
	}
}(Mask));<commit_msg>* Define Handler. Merge templates even with the empy nodes<commit_after>(function(mask){

	custom_Tags['define']  = Define;

	function Define(){}
	Define.prototype = {
		$meta: {
			serializeNodes: true
		},
		render: define,
		onRenderStartClient: define
	};

	function define(){
		var name;
		for(name in this.attr) break;

		var nodes = this.nodes;
		mask.registerHandler(name, Compo({
			renderStart: function(){
				this.nodes = mask.merge(nodes, this.nodes || [], this);
			}
		}));
	}
}(Mask));<|endoftext|>


<commit_before>import React from 'react';
import TitleEditor from '../components/titleEditor';
import BodyEditor from '../components/bodyEditor'

class Editor extends React.Component {
  constructor(props) {
    super(props);

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      title: '',
      body: ''
    }
  }
  handleChange(options) {
    let key = options.key;
    this.setState({
      [key]: options.text
    });
  }
  render() {
    return (

        <TitleEditor
          data={this.state.title}
          onChange={this.handleChange}
          limit={100}
          className="editor__title" />

        <BodyEditor
          value={this.state.body}
          onChange={this.handleChange}
          className="editor__body" />

    );
  }
}

export default Editor;<commit_msg>adds a save button<commit_after>import React from 'react';
import TitleEditor from '../components/titleEditor';
import BodyEditor from '../components/bodyEditor'

class Editor extends React.Component {
  constructor(props) {
    super(props);

    this.handleChange = this.handleChange.bind(this);

    this.state = {
      title: '',
      body: ''
    }
  }
  handleChange(options) {
    let key = options.key;
    this.setState({
      [key]: options.text
    });
  }
  handleSubmit(event) {
    event.preventDefault();
    console.log('y\'re cute, Duncan.')
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit.bind(this)} className="editor">

          <TitleEditor
            placeholder="Untitled"
            data={this.state.title}
            onChange={this.handleChange}
            limit={100}
            className="editor__title" />

          <button type="submit" className="editor__button">Save</button>

        <BodyEditor
          value={this.state.body}
          onChange={this.handleChange}
          className="editor__body" />
      </form>
    );
  }
}

export default Editor;<|endoftext|>


<commit_before>Geolocation = (function() {

  var get = function(element) {
    var disabled = function() {element.innerHTML = "DISABLED.";};
    var error    = function() {element.innerHTML = "ERROR!";   };

    if (!("geolocation" in navigator)) {
      return disabled();
    }

    navigator.geolocation.getCurrentPosition(function(pos) {
      element.innerHTML = "
" +
        pos.coords.latitude.toString()  + "
" +
        pos.coords.longitude.toString() + "
";

      var img = new Image();
      img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" +
        pos.coords.latitude  + "," +
        pos.coords.longitude + "&zoom=13&size=300x300&sensor=false";

      element.appendChild(img);
    }, error);
  };

  // Public interface:
  return {get: get};
})();
<commit_msg>Fix the name of a variable so it correctly reflects its purpose<commit_after>Geolocation = (function() {

  var get = function(element) {
    var missing = function() {element.innerHTML = "MISSING.";};
    var error   = function() {element.innerHTML = "ERROR!";   };

    if (!("geolocation" in navigator)) {
      return missing();
    }

    navigator.geolocation.getCurrentPosition(function(pos) {
      element.innerHTML = "
" +
        pos.coords.latitude.toString()  + "
" +
        pos.coords.longitude.toString() + "
";

      var img = new Image();
      img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" +
        pos.coords.latitude  + "," +
        pos.coords.longitude + "&zoom=13&size=300x300&sensor=false";

      element.appendChild(img);
    }, error);
  };

  // Public interface:
  return {get: get};
})();
<|endoftext|>


<commit_before>'use strict'

var test = require('tape')
  , lib = require('../index.js')
  , path = require('path')
  , fs = require('fs')
  , entryPath = path.join(__dirname, 'fixtures', 'watch')
  , outputPath = path.join(entryPath, 'output')
  , changerPath = path.join(outputPath, 'changer.js')
  , now = Date.now()
  , mkdirp = require('mkdirp')
  , setup = function setup () {
    var file = 'module.exports = ' + now

    mkdirp.sync(outputPath)
    fs.writeFileSync(changerPath, file)
  }

test('opts.watch', function (t) {
  var callbackCallCount = 0
    , callback
    , w

  setup()

  // get the watchify instance so that we can close it an end the test
  lib.emitter.once('watchify', function assignWatchify (watchify) {
    w = watchify
  })

  // callback will be called each time the changer file is changed
  callback = function callback (err, bundle) {
    var src = bundle.toString()
      , changerContents2 = 'module.exports = changed'

    callbackCallCount++

    // first call only
    if (callbackCallCount === 1){
      t.error(err, 'does not error on initial callback')

      t.ok(
        src.indexOf(now) > -1
        , 'contains the watched dep on inital callback'
      )

      // commit a change to the file so that we trigger the callback again
      fs.writeFile(changerPath, changerContents2)
    }
    else {
      // close all file handlers ← important so that tests exit
      w.close()

      t.error(err, 'does not error on the second callback')

      t.ok(
        src.indexOf(changerContents2) > -1
        , 'contains the watched dep on the second callback'
      )

      // hack around this test never ending… not really sure why that happens
      t.end()
      process.exit(0)
    }
  }

  // run the lib with watchify enabled
  // wait just a bit to ensure all the file watchers are in place
  setTimeout(function () {
    lib({watch: true, entry: path.join(entryPath, 'index.js')}, callback)
  }, 50)
})
<commit_msg>internal: fix watch test not finishing<commit_after>'use strict'

var test = require('tape')
  , lib = require('../index.js')
  , path = require('path')
  , fs = require('fs')
  , entryPath = path.join(__dirname, 'fixtures', 'watch')
  , outputPath = path.join(entryPath, 'output')
  , changerPath = path.join(outputPath, 'changer.js')
  , now = Date.now()
  , mkdirp = require('mkdirp')
  , setup = function setup () {
    var file = 'module.exports = ' + now

    mkdirp.sync(outputPath)
    fs.writeFileSync(changerPath, file)
  }

test('opts.watch', function (t) {
  var callbackCallCount = 0
    , callback
    , w

  setup()

  // get the watchify instance so that we can close it an end the test
  lib.emitter.once('watchify', function assignWatchify (watchify) {
    w = watchify
  })

  // callback will be called each time the changer file is changed
  callback = function callback (err, bundle) {
    var src = bundle.toString()
      , changerContents2 = 'module.exports = changed'

    callbackCallCount++

    // first call only
    if (callbackCallCount === 1){
      t.error(err, 'does not error on initial callback')

      t.ok(
        src.indexOf(now) > -1
        , 'contains the watched dep on inital callback'
      )

      // wait for a bit to write the file because watchify has a delay
      setTimeout(function () {
        // commit a change to the file so that we trigger the callback again
        fs.writeFile(changerPath, changerContents2)
      }, 600)
    }
    else {
      // close all file handlers ← important so that tests exit
      w.close()

      t.error(err, 'does not error on the second callback')

      t.ok(
        src.indexOf(changerContents2) > -1
        , 'contains the watched dep on the second callback'
      )

      // hack around this test never ending… not really sure why that happens
      t.end()
      process.exit(0)
    }
  }

  // run the lib with watchify enabled
  // wait just a bit to ensure all the file watchers are in place
  setTimeout(function () {
    lib({watch: true, entry: path.join(entryPath, 'index.js')}, callback)
  }, 50)
})
<|endoftext|>