<commit_before>describe("m.trust()", function () {
	"use strict"

	it("exists", function () {
		expect(m.trust).to.be.a("function")
	})

	it("returns an instance of String", function () {
		expect(m.trust("foo")).to.be.an.instanceof(String)
	})

	it("does not modify the string", function () {
		expect(m.trust("foo").valueOf()).to.equal("foo")
	})

	it("is not identical to the string", function () {
		expect(m.trust("foo")).to.not.equal("foo")
	})

	// FIXME: implement document.createRange().createContextualFragment() in the
	// mock window for these tests
	dom(function () {
		it("isn't escaped in m.render()", function () {
			var root = document.createElement("div")
			m.render(root, m("div", "a", m.trust("&"), "b"))
			expect(root.childNodes[0].innerHTML).to.equal("a&b")
		})

		it("works with mixed trusted content in div", function () {
			var root = document.createElement("div")
			m.render(root, [m.trust("
1

2
"), m("i", "foo")])
			expect(root.childNodes[2].tagName).to.equal("I")
		})

		it("works with mixed trusted content in text nodes", function () {
			var root = document.createElement("div")
			m.render(root, [
				m.trust("
1
123
2
"),
				m("i", "foo")
			])
			expect(root.childNodes[3].tagName).to.equal("I")
		})

		// TODO: this currently fails.
		xit("works with mixed trusted content in td", function () {
			var root = document.createElement("table")
			root.appendChild(root = document.createElement("tr"))

			m.render(root, [
				m.trust("1	2	"),
				m("td", "foo")
			])

			expect(root.childNodes[2].tagName).to.equal("TD")
		})

		it("works with trusted content in div", function () {
			var root = document.createElement("div")
			m.render(root, m("div", [
				m("p", "©"),
				m("p", m.trust("©")),
				m.trust("©")
			]))

			expect(root.innerHTML)
				.to.equal("

&copy;

©
©
")
		})
	})
})
<commit_msg>Clarify why a test is broken. [ci skip]<commit_after>describe("m.trust()", function () {
	"use strict"

	it("exists", function () {
		expect(m.trust).to.be.a("function")
	})

	it("returns an instance of String", function () {
		expect(m.trust("foo")).to.be.an.instanceof(String)
	})

	it("does not modify the string", function () {
		expect(m.trust("foo").valueOf()).to.equal("foo")
	})

	it("is not identical to the string", function () {
		expect(m.trust("foo")).to.not.equal("foo")
	})

	// FIXME: implement document.createRange().createContextualFragment() in the
	// mock window for these tests
	dom(function () {
		it("isn't escaped in m.render()", function () {
			var root = document.createElement("div")
			m.render(root, m("div", "a", m.trust("&"), "b"))
			expect(root.childNodes[0].innerHTML).to.equal("a&b")
		})

		it("works with mixed trusted content in div", function () {
			var root = document.createElement("div")
			m.render(root, [m.trust("
1

2
"), m("i", "foo")])
			expect(root.childNodes[2].tagName).to.equal("I")
		})

		it("works with mixed trusted content in text nodes", function () {
			var root = document.createElement("div")
			m.render(root, [
				m.trust("
1
123
2
"),
				m("i", "foo")
			])
			expect(root.childNodes[3].tagName).to.equal("I")
		})

		// TODO: m.trust's contents are having their tags stripped.
		xit("works with mixed trusted content in td", function () {
			var root = document.createElement("table")
			root.appendChild(root = document.createElement("tr"))

			m.render(root, [
				m.trust("1	2	"),
				m("td", "foo")
			])

			expect(root.childNodes[2].tagName).to.equal("TD")
		})

		it("works with trusted content in div", function () {
			var root = document.createElement("div")
			m.render(root, m("div", [
				m("p", "©"),
				m("p", m.trust("©")),
				m.trust("©")
			]))

			expect(root.innerHTML)
				.to.equal("

&copy;

©
©
")
		})
	})
})
<|endoftext|>


<commit_before>var sinon = require('sinon');
var chai = require('chai');

var should = chai.should();
chai.Assertion.includeStack = true;
chai.use(require('sinon-chai'));

var conjure = require('../../dist/conjure');
var Conjure = conjure.Conjure;
var requireComponent = conjure.require;

requireComponent('sinon-doublist')(sinon, 'mocha');

describe('helpers', function() {
  'use strict';

  /**
   * Pack any remotely reusable boilerplate here to keep the actual tests
   * as small/clear as possible.
   */
  beforeEach(function() {
    this.stubs = {};
    addStubTargets.call(this);
    stubRequire.call(this);
    stubConjure.call(this);
    stubWindow.call(this);
    stubJQuery.call(this);
    addFixtures.call(this);
    stubUtilsApi.call(this);
    stubTestApi.call(this);
    stubCasperApi.call(this);
    stubThenMethods.call(this);
    stubMisc.call(this);
  });

  describe('click', function() {
    beforeEach(function() {
      this.stubs.casper.thenEvaluate.yields(this.sel);
      this.stubs.conjure.click.restore();
      this.conjure.click(this.sel);
    });
    it('should wait for selector match' , function() {
      this.stubs.conjure.selectorExists.calledWithExactly(this.sel);
    });
    it('should use jQuery to click' , function() {
      this.stubs.casper.thenEvaluate.should.be.called;
      this.stubs.$global.should.have.been.calledWithExactly(this.sel);
      this.stubs.$.click.should.have.been.called;
    });
  });

  describe('then', function() {
    beforeEach(function() {
      this.stubs.conjure.then.restore();
      this.conjure.then(this.stubs.cb);
    });
    it('should inject context' , function() {
      this.stubs.extend.should.have.been.calledWith(
        this.createdContext,
        {casper: this.conjure.casper, test: this.testApi}
      );
      this.stubs.cb.should.have.been.calledOn(this.extendResult);
    });
  });

  describe('assertSelText', function() {
    beforeEach(function() {
      this.stubs.conjure.assertSelText.restore();
      this.restoreComponentRequire();
    });
    it('should use jQuery text()' , function() {
      this.conjure.assertSelText(this.sel, this.textNeedle);
      this.stubs.test.assertEquals.should.have.been.calledWithExactly(
        this.evaluateResult,
        this.textNeedle
      );
    });
    it('should support regex' , function() {
      this.conjure.assertSelText(this.sel, this.reNeedle);
      this.stubs.test.assertMatch.should.have.been.calledWithExactly(
        this.evaluateResult,
        this.reNeedle
      );
    });
  });

  describe('assertType', function() {
    beforeEach(function() {
      this.stubs.conjure.assertType.restore();
    });
    it('should use assertEquals()' , function() {
      this.conjure.assertType(this.sel, 'string');
      this.stubs.utils.betterTypeOf.should.have.been.calledWithExactly(this.sel);
      this.stubs.utils.format.should.have.been.calledWithExactly(
        '%s should be a %s', 'subject', 'string'
      );
      this.stubs.test.assertEquals.should.have.been.calledWithExactly(
        this.betterTypeOf,
        'string',
        this.format
      );
    });
    it('should apply custom subject label' , function() {
      var subject = 'testString';
      this.conjure.assertType(this.sel, 'string', subject);
      this.stubs.utils.format.should.have.been.calledWithExactly(
        '%s should be a %s', subject, 'string'
      );
    });
  });

  describe('each', function() {
    beforeEach(function() {
      this.stubs.conjure.each.restore();
    });
    it('should invoke callback inside custom then()' , function() {
      var self = this;
      this.conjure.each(this.strList, this.stubs.cb);
      this.stubs.cb.should.have.been.calledOn(this.thenContext);
      this.strList.forEach(function(item) {
        self.stubs.cb.should.have.been.calledWithExactly(item);
      });
    });
  });

  describe('openHash', function() {
    beforeEach(function() {
      this.stubs.conjure.openHash.restore();
      this.hash = 'top';
      this.fullHash = '#' + this.hash;
      this.stubs.casper.thenEvaluate.yields(this.hash);
    });
    it('should update location hash' , function() {
      this.conjure.openHash(this.hash);
      window.location.hash.should.equal(this.fullHash);
    });
    it('should optionally wait for a selector to exist' , function() {
      this.conjure.openHash(this.hash, this.sel);
      this.stubs.conjure.selectorExists.should.have.been.calledWithExactly(this.sel);
    });
  });

  describe('openInitUrl', function() {
    beforeEach(function() {
      this.stubs.conjure.openInitUrl.restore();
    });
    it('should use thenOpen()' , function() {
      this.conjure.openInitUrl();
      this.stubs.casper.thenOpen.should.have.been.calledWithExactly(
        'http://localhost:8174/'
      );
    });
  });
});

/**
 * Organize, and isolate from beforeEach(), for sanity.
 */

function addStubTargets() {
  this.testApi = {}; // CasperJS's this.test API
  this.utilsApi = {}; // CasperJS's this.utils API
  this.extendResult = {iAmA: 'extend() component'};
  this.createdContext = {iAmA: 'createdContext() return value'};
  this.requiredComponent = {iAmA: 'component-land require() return value'};
  this.evaluateResult = {iAmA: 'casper.evaluate() return value'};
  this.betterTypeOf = {iAmA: 'utils.betterTypeOf() return value'};
  this.format = {iAmA: 'utils.format() return value'};
}

function stubRequire() {
  // Stubbing CasperJS-land require(), ex. for colorizer module
  this.stubs.requiredComponentCreate = this.stubMany(
    this.requiredComponent, 'create'
  ).create;
  this.stubs.casperRequire = this.stub();
  this.stubs.casperRequire.returns(this.requiredComponent);

  this.stubs.extend = this.stub();
  this.stubs.extend.returns(this.extendResult);
  this.stubs.require = this.stub(conjure, 'require');
  this.stubs.require.withArgs('extend').returns(this.stubs.extend);
  conjure.setRequire(this.stubs.require);
  this.restoreComponentRequire = function() {
    conjure.setRequire(requireComponent);
  };
}

function stubConjure() {
  this.conjure = conjure.create(this.stubs.casperRequire);
  this.stubs.conjure = this.stub(this.conjure.conjure);
}

function stubWindow() {
  GLOBAL.window = {
    location: {
      hash: ''
    }
  };
}

function stubJQuery() {
  // Use for stubs like: $(sel).<some method>().
  this.stubs.$result = {};

  // Use this.$stub to know what selector $ received.
  GLOBAL.$ = function() {};
  this.stubs.$global = this.stub(GLOBAL, '$').returns(this.stubs.$result);

  this.stubs.$ = this.stubMany(
    this.stubs.$result,
    [
      'click', 'text'
    ]
  );
}

function addFixtures() {
  this.sel = '.klass';
  this.textNeedle = 'foo';
  this.reNeedle = /foo/;
  this.stubs.cb = this.stub();
  this.strList = ['one', 'two', 'three'];
}

function stubUtilsApi() {
  this.stubs.utils = this.stubMany(
    this.utilsApi,
    [
      'betterTypeOf', 'format'
    ]
  );
  this.stubs.utils.betterTypeOf.returns(this.betterTypeOf);
  this.stubs.utils.format.returns(this.format);
}

function stubTestApi() {
  this.stubs.test = this.stubMany(
    this.testApi,
    [
      'assertEquals', 'assertMatch'
    ]
  );
}

function stubCasperApi() {
  this.conjure.casper = {};
  this.stubs.casper = this.stubMany(
    this.conjure.casper,
    [
      'evaluate', 'then', 'thenEvaluate', 'thenOpen'
    ]
  );
  this.stubs.casper.evaluate.returns(this.evaluateResult);
}

function stubThenMethods() {
  this.thenContext = {
    test: this.stubs.test,
    evaluate: this.stubs.casper.evaluate,
    utils: this.stubs.utils
  };
  this.stubs.casper.then.yieldsOn(this.thenContext);
  this.stubs.conjure.then.yieldsOn(this.thenContext);
}

function stubMisc() {
  this.stubs.createContext = this.stub(Conjure, 'createContext');
  this.stubs.createContext.returns(this.createdContext);
}
<commit_msg>test(mixins): Cover require()<commit_after>var sinon = require('sinon');
var chai = require('chai');

var should = chai.should();
chai.Assertion.includeStack = true;
chai.use(require('sinon-chai'));

var conjure = require('../../dist/conjure');
var Conjure = conjure.Conjure;
var requireComponent = conjure.require;

requireComponent('sinon-doublist')(sinon, 'mocha');

describe('helpers', function() {
  'use strict';

  /**
   * Pack any remotely reusable boilerplate here to keep the actual tests
   * as small/clear as possible.
   */
  beforeEach(function() {
    this.stubs = {};
    addStubTargets.call(this);
    stubRequire.call(this);
    stubConjure.call(this);
    stubWindow.call(this);
    stubJQuery.call(this);
    addFixtures.call(this);
    stubUtilsApi.call(this);
    stubTestApi.call(this);
    stubCasperApi.call(this);
    stubThenMethods.call(this);
    stubMisc.call(this);
  });

  describe('click', function() {
    beforeEach(function() {
      this.stubs.casper.thenEvaluate.yields(this.sel);
      this.stubs.helper.click.restore();
      this.conjure.click(this.sel);
    });
    it('should wait for selector match' , function() {
      this.stubs.helper.selectorExists.calledWithExactly(this.sel);
    });
    it('should use jQuery to click' , function() {
      this.stubs.casper.thenEvaluate.should.be.called;
      this.stubs.$global.should.have.been.calledWithExactly(this.sel);
      this.stubs.$.click.should.have.been.called;
    });
  });

  describe('then', function() {
    beforeEach(function() {
      this.stubs.helper.then.restore();
      this.conjure.then(this.stubs.cb);
    });
    it('should inject context' , function() {
      this.stubs.extend.should.have.been.calledWith(
        this.createdContext,
        {casper: this.conjure.casper, test: this.testApi}
      );
      this.stubs.cb.should.have.been.calledOn(this.extendResult);
    });
  });

  describe('assertSelText', function() {
    beforeEach(function() {
      this.stubs.helper.assertSelText.restore();
      this.restoreComponentRequire();
    });
    it('should use jQuery text()' , function() {
      this.conjure.assertSelText(this.sel, this.textNeedle);
      this.stubs.test.assertEquals.should.have.been.calledWithExactly(
        this.evaluateResult,
        this.textNeedle
      );
    });
    it('should support regex' , function() {
      this.conjure.assertSelText(this.sel, this.reNeedle);
      this.stubs.test.assertMatch.should.have.been.calledWithExactly(
        this.evaluateResult,
        this.reNeedle
      );
    });
  });

  describe('assertType', function() {
    beforeEach(function() {
      this.stubs.helper.assertType.restore();
    });
    it('should use assertEquals()' , function() {
      this.conjure.assertType(this.sel, 'string');
      this.stubs.utils.betterTypeOf.should.have.been.calledWithExactly(this.sel);
      this.stubs.utils.format.should.have.been.calledWithExactly(
        '%s should be a %s', 'subject', 'string'
      );
      this.stubs.test.assertEquals.should.have.been.calledWithExactly(
        this.betterTypeOf,
        'string',
        this.format
      );
    });
    it('should apply custom subject label' , function() {
      var subject = 'testString';
      this.conjure.assertType(this.sel, 'string', subject);
      this.stubs.utils.format.should.have.been.calledWithExactly(
        '%s should be a %s', subject, 'string'
      );
    });
  });

  describe('each', function() {
    beforeEach(function() {
      this.stubs.helper.each.restore();
    });
    it('should invoke callback inside custom then()' , function() {
      var self = this;
      this.conjure.each(this.strList, this.stubs.cb);
      this.stubs.cb.should.have.been.calledOn(this.thenContext);
      this.strList.forEach(function(item) {
        self.stubs.cb.should.have.been.calledWithExactly(item);
      });
    });
  });

  describe('openHash', function() {
    beforeEach(function() {
      this.stubs.helper.openHash.restore();
      this.hash = 'top';
      this.fullHash = '#' + this.hash;
      this.stubs.casper.thenEvaluate.yields(this.hash);
    });
    it('should update location hash' , function() {
      this.conjure.openHash(this.hash);
      window.location.hash.should.equal(this.fullHash);
    });
    it('should optionally wait for a selector to exist' , function() {
      this.conjure.openHash(this.hash, this.sel);
      this.stubs.helper.selectorExists.should.have.been.calledWithExactly(this.sel);
    });
  });

  describe('openInitUrl', function() {
    beforeEach(function() {
      this.stubs.helper.openInitUrl.restore();
      this.stubs.conjure.get.restore();
    });
    it('should use thenOpen()' , function() {
      this.conjure.openInitUrl();
      this.stubs.casper.thenOpen.should.have.been.calledWithExactly(
        'http://localhost:8174/'
      );
    });
  });

  describe('require', function() {
    beforeEach(function() {
      this.stubs.helper.require.restore();
    });
    it('should detect local path' , function() {
      var path = 'lib/sub/module.js';
      this.conjure.require('./' + path);
      this.stubs.casperRequire.should.have.been.calledWithExactly(
        this.cliApi.options.rootdir + '/' + path
      );
    });
  });
});

/**
 * Organize, and isolate from beforeEach(), for sanity.
 */

function addStubTargets() {
  this.testApi = {}; // CasperJS's this.test API
  this.utilsApi = {}; // CasperJS's this.utils API
  this.cliApi = { // CasperJS's CLI API
    options: {
      rootdir: '/path/to/proj'
    }
  };
  this.extendResult = {iAmA: 'extend() component'};
  this.createdContext = {iAmA: 'createdContext() return value'};
  this.requiredComponent = {iAmA: 'component-land require() return value'};
  this.evaluateResult = {iAmA: 'casper.evaluate() return value'};
  this.betterTypeOf = {iAmA: 'utils.betterTypeOf() return value'};
  this.format = {iAmA: 'utils.format() return value'};
}

function stubRequire() {
  // Stubbing CasperJS-land require(), ex. for colorizer module
  this.stubs.requiredComponentCreate = this.stubMany(
    this.requiredComponent, 'create'
  ).create;
  this.stubs.casperRequire = this.stub();
  this.stubs.casperRequire.returns(this.requiredComponent);

  this.stubs.extend = this.stub();
  this.stubs.extend.returns(this.extendResult);
  this.stubs.require = this.stub(conjure, 'require');
  this.stubs.require.withArgs('extend').returns(this.stubs.extend);
  conjure.setRequire(this.stubs.require);
  this.restoreComponentRequire = function() {
    conjure.setRequire(requireComponent);
  };
}

function stubConjure() {
  this.conjure = conjure.create(this.stubs.casperRequire);
  this.stubs.helper = this.stub(this.conjure.conjure);

  this.stubConfig = function(key, val) {
    this.stubs.conjure.get.withArgs(key).returns(val);
  };

  this.stubs.conjure = {
    get: this.stub(this.conjure, 'get')
  };
  this.stubConfig('cli', this.cliApi);
  this.stubConfig('casperRequire', this.stubs.casperRequire);
}

function stubWindow() {
  GLOBAL.window = {
    location: {
      hash: ''
    }
  };
}

function stubJQuery() {
  // Use for stubs like: $(sel).<some method>().
  this.stubs.$result = {};

  // Use this.$stub to know what selector $ received.
  GLOBAL.$ = function() {};
  this.stubs.$global = this.stub(GLOBAL, '$').returns(this.stubs.$result);

  this.stubs.$ = this.stubMany(
    this.stubs.$result,
    [
      'click', 'text'
    ]
  );
}

function addFixtures() {
  this.sel = '.klass';
  this.textNeedle = 'foo';
  this.reNeedle = /foo/;
  this.stubs.cb = this.stub();
  this.strList = ['one', 'two', 'three'];
}

function stubUtilsApi() {
  this.stubs.utils = this.stubMany(
    this.utilsApi,
    [
      'betterTypeOf', 'format'
    ]
  );
  this.stubs.utils.betterTypeOf.returns(this.betterTypeOf);
  this.stubs.utils.format.returns(this.format);
}

function stubTestApi() {
  this.stubs.test = this.stubMany(
    this.testApi,
    [
      'assertEquals', 'assertMatch'
    ]
  );
}

function stubCasperApi() {
  this.conjure.casper = {};
  this.stubs.casper = this.stubMany(
    this.conjure.casper,
    [
      'evaluate', 'then', 'thenEvaluate', 'thenOpen'
    ]
  );
  this.stubs.casper.evaluate.returns(this.evaluateResult);
}

function stubThenMethods() {
  this.thenContext = {
    test: this.stubs.test,
    evaluate: this.stubs.casper.evaluate,
    utils: this.stubs.utils
  };
  this.stubs.casper.then.yieldsOn(this.thenContext);
  this.stubs.helper.then.yieldsOn(this.thenContext);
}

function stubMisc() {
  this.stubs.createContext = this.stub(Conjure, 'createContext');
  this.stubs.createContext.returns(this.createdContext);
}
<|endoftext|>


<commit_before>/* global module, asyncTest, $, ok, equal, notEqual, start, test, Util, testLog */

(function () {
    var viewer;

    module('Units', {
        setup: function () {
            var example = $('

').appendTo("#qunit-fixture");

            testLog.reset();

            viewer = OpenSeadragon({
                id: 'unitsexample',
                prefixUrl: '/build/openseadragon/images/',
                springStiffness: 100 // Faster animation = faster tests
            });
        },
        teardown: function () {
            if (viewer && viewer.close) {
                viewer.close();
            }

            viewer = null;
        }
    });

    function pointEqual(a, b, message) {
        Util.assessNumericValue(a.x, b.x, 0.00000001, message);
        Util.assessNumericValue(a.y, b.y, 0.00000001, message);
    }

    // Check that f^-1 ( f(x) ) = x
    function checkPoint(context) {
        var viewport = viewer.viewport;

        var point = new OpenSeadragon.Point(15, 12);
        var result = viewport.viewerElementToImageCoordinates(
                viewport.imageToViewerElementCoordinates(point));
        pointEqual(result, point, 'viewerElement and image ' + context);

        result = viewport.windowToImageCoordinates(
                viewport.imageToWindowCoordinates(point));
        pointEqual(result, point, 'window and image ' + context);

        result = viewport.viewerElementToViewportCoordinates(
                viewport.viewportToViewerElementCoordinates(point));
        pointEqual(result, point, 'viewerElement and viewport ' + context);

        result = viewport.windowToViewportCoordinates(
                viewport.viewportToWindowCoordinates(point));
        pointEqual(result, point, 'window and viewport ' + context);

        for (var i = 0; i < viewer.world.getItemCount(); i++) {
            var tiledImage = viewer.world.getItemAt(i);
            result = tiledImage.viewportToImageCoordinates(
                    tiledImage.imageToViewportCoordinates(point));
            pointEqual(result, point, 'viewport and tiled image ' + i + context);

            result = tiledImage.viewerElementToImageCoordinates(
                    tiledImage.imageToViewerElementCoordinates(point));
            pointEqual(result, point, 'viewerElement and tiled image ' + i + context);

            result = tiledImage.windowToImageCoordinates(
                    tiledImage.imageToWindowCoordinates(point));
            pointEqual(result, point, 'window and tiled image ' + i + context);
        }
    }

    // ----------
    asyncTest('Single image coordinates conversions', function () {

        viewer.addHandler("open", function () {
            var viewport = viewer.viewport;
            var tiledImage = viewer.world.getItemAt(0);

            var point0_0 = new OpenSeadragon.Point(0, 0);
            var point = viewport.viewerElementToViewportCoordinates(point0_0);
            pointEqual(point, point0_0, 'When opening, viewer coordinate 0,0 is also point 0,0');
            var viewportPixel = viewport.viewerElementToImageCoordinates(point0_0);
            pointEqual(viewportPixel, point0_0, 'When opening, viewer coordinate 0,0 is also viewport pixel 0,0');
            var imagePixel = tiledImage.viewerElementToImageCoordinates(point0_0);
            pointEqual(imagePixel, point0_0, 'When opening, viewer coordinate 0,0 is also image pixel 0,0');

            var viewerWidth = $(viewer.element).width();
            var imageWidth = viewer.source.dimensions.x;
            var point1_0 = new OpenSeadragon.Point(1, 0);
            var viewerTopRight = new OpenSeadragon.Point(viewerWidth, 0);
            var imageTopRight = new OpenSeadragon.Point(imageWidth, 0);

            point = viewport.viewerElementToViewportCoordinates(viewerTopRight);
            pointEqual(point, point1_0, 'Viewer top right has viewport coordinates 1,0.');
            viewportPixel = viewport.viewerElementToImageCoordinates(viewerTopRight);
            pointEqual(viewportPixel, imageTopRight, 'Viewer top right has viewport pixel coordinates imageWidth,0.');
            imagePixel = tiledImage.viewerElementToImageCoordinates(viewerTopRight);
            pointEqual(imagePixel, imageTopRight, 'Viewer top right has image pixel coordinates imageWidth,0.');

            checkPoint(' after opening');
            viewer.addHandler('animation-finish', function animationHandler() {
                viewer.removeHandler('animation-finish', animationHandler);
                checkPoint(' after zoom and pan');
                start();
            });
            viewer.viewport.zoomTo(0.8).panTo(new OpenSeadragon.Point(0.1, 0.2));
        });
        viewer.open('/test/data/testpattern.dzi');
    });

    // ---------
    asyncTest('Multiple images coordinates conversion', function () {

        viewer.addHandler("open", function () {
            var viewport = viewer.viewport;
            var tiledImage1 = viewer.world.getItemAt(0);
            var tiledImage2 = viewer.world.getItemAt(1);
            var imageWidth = viewer.source.dimensions.x;
            var imageHeight = viewer.source.dimensions.y;

            var point0_0 = new OpenSeadragon.Point(0, 0);
            var point = viewport.viewerElementToViewportCoordinates(point0_0);
            pointEqual(point, point0_0, 'When opening, viewer coordinate 0,0 is also point 0,0');
            var image1Pixel = tiledImage1.viewerElementToImageCoordinates(point0_0);
            pointEqual(image1Pixel, point0_0, 'When opening, viewer coordinate 0,0 is also image 1 pixel 0,0');
            var image2Pixel = tiledImage2.viewerElementToImageCoordinates(point0_0);
            pointEqual(image2Pixel,
                    new OpenSeadragon.Point(-2 * imageWidth, -2 * imageHeight),
                    'When opening, viewer coordinates 0,0 is also image 2 pixel -2*imageWidth, -2*imageHeight');

            var viewerWidth = $(viewer.element).width();
            var viewerHeight = $(viewer.element).height();
            var viewerBottomRight = new OpenSeadragon.Point(viewerWidth, viewerHeight);

            point = viewport.viewerElementToViewportCoordinates(viewerBottomRight);
            pointEqual(point, new OpenSeadragon.Point(1.5, 1.5),
                    'Viewer bottom right has viewport coordinates 1.5,1.5.');
            image1Pixel = tiledImage1.viewerElementToImageCoordinates(viewerBottomRight);
            pointEqual(image1Pixel,
                    new OpenSeadragon.Point(imageWidth * 1.5, imageHeight * 1.5),
                    'Viewer bottom right has image 1 pixel coordinates imageWidth * 1.5, imageHeight * 1.5');
            image2Pixel = tiledImage2.viewerElementToImageCoordinates(viewerBottomRight);
            pointEqual(image2Pixel,
                    new OpenSeadragon.Point(imageWidth, imageHeight),
                    'Viewer bottom right has image 2 pixel coordinates imageWidth,imageHeight.');

            checkPoint(' after opening');
            viewer.addHandler('animation-finish', function animationHandler() {
                viewer.removeHandler('animation-finish', animationHandler);
                checkPoint(' after zoom and pan');
                start();
            });
            viewer.viewport.zoomTo(0.8).panTo(new OpenSeadragon.Point(0.1, 0.2));

            start();
        });

        viewer.open([{
                tileSource: "/test/data/testpattern.dzi"
            }, {
                tileSource: "/test/data/testpattern.dzi",
                x: 1,
                y: 1,
                width: 0.5
            }
        ]);
    });

    // ----------
    asyncTest('ZoomRatio 1 image', function () {
        viewer.addHandler("open", function () {

            var viewport = viewer.viewport;

            var imageWidth = viewer.source.dimensions.x;

            function getCurrentImageWidth() {
                return viewport.viewportToViewerElementCoordinates(
                        new OpenSeadragon.Point(1, 0)).minus(
                        viewport.viewportToViewerElementCoordinates(
                                new OpenSeadragon.Point(0, 0))).x;
            }

            function checkZoom() {
                var currentImageWidth = getCurrentImageWidth();
                var expectedImageZoom = currentImageWidth / imageWidth;
                var expectedViewportZoom = viewport.getZoom(true);
                var actualImageZoom = viewport.viewportToImageZoom(
                        expectedViewportZoom);
                equal(actualImageZoom, expectedImageZoom);

                var actualViewportZoom = viewport.imageToViewportZoom(actualImageZoom);
                equal(actualViewportZoom, expectedViewportZoom);
            }

            checkZoom();

            var zoomHandler = function () {
                viewer.removeHandler('animation-finish', zoomHandler);
                checkZoom();
                start();
            };

            viewer.addHandler('animation-finish', zoomHandler);
            viewport.zoomTo(2);
        });

        viewer.open('/test/data/testpattern.dzi');
    });

    // ----------
    asyncTest('ZoomRatio 2 images', function () {
        viewer.addHandler("open", function () {

            var viewport = viewer.viewport;

            var imageWidth = viewer.source.dimensions.x;
            var image1 = viewer.world.getItemAt(0);
            var image2 = viewer.world.getItemAt(1);

            function getCurrentImageWidth(image) {
                var bounds = image.getBounds();
                return viewport.viewportToViewerElementCoordinates(
                        bounds.getTopRight()).minus(
                        viewport.viewportToViewerElementCoordinates(
                                bounds.getTopLeft())).x;
            }

            function checkZoom(image) {
                var currentImageWidth = getCurrentImageWidth(image);
                var expectedImageZoom = currentImageWidth / imageWidth;
                var expectedViewportZoom = viewport.getZoom(true);
                var actualImageZoom = image.viewportToImageZoom(
                        expectedViewportZoom);
                Util.assessNumericValue(actualImageZoom, expectedImageZoom,
                        0.00000001);

                var actualViewportImage1Zoom = image.imageToViewportZoom(actualImageZoom);
                Util.assessNumericValue(
                        actualViewportImage1Zoom, expectedViewportZoom, 0.00000001);
            }

            checkZoom(image1);
            checkZoom(image2);

            var zoomHandler = function () {
                viewer.removeHandler('animation-finish', zoomHandler);
                checkZoom(image1);
                checkZoom(image2);
                start();
            };

            viewer.addHandler('animation-finish', zoomHandler);
            viewport.zoomTo(2);
        });

        viewer.open([{
                tileSource: "/test/data/testpattern.dzi"
            }, {
                tileSource: "/test/data/testpattern.dzi",
                x: 1,
                y: 1,
                width: 0.5
            }
        ]);
    });

})();
<commit_msg>Add units conversion with rotation unit tests.<commit_after>/* global module, asyncTest, $, ok, equal, notEqual, start, test, Util, testLog */

(function () {
    var viewer;
    var precision = 0.00000001;

    module('Units', {
        setup: function () {
            var example = $('

').appendTo("#qunit-fixture");

            testLog.reset();

            viewer = OpenSeadragon({
                id: 'unitsexample',
                prefixUrl: '/build/openseadragon/images/',
                springStiffness: 100 // Faster animation = faster tests
            });
        },
        teardown: function () {
            if (viewer && viewer.close) {
                viewer.close();
            }

            viewer = null;
        }
    });

    function pointEqual(a, b, message) {
        Util.assessNumericValue(a.x, b.x, precision, message);
        Util.assessNumericValue(a.y, b.y, precision, message);
    }

    // Check that f^-1 ( f(x) ) = x
    function checkPoint(context) {
        var viewport = viewer.viewport;

        var point = new OpenSeadragon.Point(15, 12);
        var result = viewport.viewerElementToImageCoordinates(
                viewport.imageToViewerElementCoordinates(point));
        pointEqual(result, point, 'viewerElement and image ' + context);

        result = viewport.windowToImageCoordinates(
                viewport.imageToWindowCoordinates(point));
        pointEqual(result, point, 'window and image ' + context);

        result = viewport.viewerElementToViewportCoordinates(
                viewport.viewportToViewerElementCoordinates(point));
        pointEqual(result, point, 'viewerElement and viewport ' + context);

        result = viewport.windowToViewportCoordinates(
                viewport.viewportToWindowCoordinates(point));
        pointEqual(result, point, 'window and viewport ' + context);

        for (var i = 0; i < viewer.world.getItemCount(); i++) {
            var tiledImage = viewer.world.getItemAt(i);
            result = tiledImage.viewportToImageCoordinates(
                    tiledImage.imageToViewportCoordinates(point));
            pointEqual(result, point, 'viewport and tiled image ' + i + context);

            result = tiledImage.viewerElementToImageCoordinates(
                    tiledImage.imageToViewerElementCoordinates(point));
            pointEqual(result, point, 'viewerElement and tiled image ' + i + context);

            result = tiledImage.windowToImageCoordinates(
                    tiledImage.imageToWindowCoordinates(point));
            pointEqual(result, point, 'window and tiled image ' + i + context);
        }
    }

    // ----------
    asyncTest('Single image coordinates conversions', function () {

        viewer.addHandler("open", function () {
            var viewport = viewer.viewport;
            var tiledImage = viewer.world.getItemAt(0);

            var point0_0 = new OpenSeadragon.Point(0, 0);
            var point = viewport.viewerElementToViewportCoordinates(point0_0);
            pointEqual(point, point0_0, 'When opening, viewer coordinate 0,0 is also point 0,0');
            var viewportPixel = viewport.viewerElementToImageCoordinates(point0_0);
            pointEqual(viewportPixel, point0_0, 'When opening, viewer coordinate 0,0 is also viewport pixel 0,0');
            var imagePixel = tiledImage.viewerElementToImageCoordinates(point0_0);
            pointEqual(imagePixel, point0_0, 'When opening, viewer coordinate 0,0 is also image pixel 0,0');

            var viewerWidth = $(viewer.element).width();
            var imageWidth = viewer.source.dimensions.x;
            var point1_0 = new OpenSeadragon.Point(1, 0);
            var viewerTopRight = new OpenSeadragon.Point(viewerWidth, 0);
            var imageTopRight = new OpenSeadragon.Point(imageWidth, 0);

            point = viewport.viewerElementToViewportCoordinates(viewerTopRight);
            pointEqual(point, point1_0, 'Viewer top right has viewport coordinates 1,0.');
            viewportPixel = viewport.viewerElementToImageCoordinates(viewerTopRight);
            pointEqual(viewportPixel, imageTopRight, 'Viewer top right has viewport pixel coordinates imageWidth,0.');
            imagePixel = tiledImage.viewerElementToImageCoordinates(viewerTopRight);
            pointEqual(imagePixel, imageTopRight, 'Viewer top right has image pixel coordinates imageWidth,0.');

            checkPoint(' after opening');
            viewer.addHandler('animation-finish', function animationHandler() {
                viewer.removeHandler('animation-finish', animationHandler);
                checkPoint(' after zoom and pan');
                start();
            });
            viewer.viewport.zoomTo(0.8).panTo(new OpenSeadragon.Point(0.1, 0.2));
        });
        viewer.open('/test/data/testpattern.dzi');
    });

    // ---------
    asyncTest('Multiple images coordinates conversion', function () {

        viewer.addHandler("open", function () {
            var viewport = viewer.viewport;
            var tiledImage1 = viewer.world.getItemAt(0);
            var tiledImage2 = viewer.world.getItemAt(1);
            var imageWidth = viewer.source.dimensions.x;
            var imageHeight = viewer.source.dimensions.y;

            var point0_0 = new OpenSeadragon.Point(0, 0);
            var point = viewport.viewerElementToViewportCoordinates(point0_0);
            pointEqual(point, point0_0, 'When opening, viewer coordinate 0,0 is also point 0,0');
            var image1Pixel = tiledImage1.viewerElementToImageCoordinates(point0_0);
            pointEqual(image1Pixel, point0_0, 'When opening, viewer coordinate 0,0 is also image 1 pixel 0,0');
            var image2Pixel = tiledImage2.viewerElementToImageCoordinates(point0_0);
            pointEqual(image2Pixel,
                    new OpenSeadragon.Point(-2 * imageWidth, -2 * imageHeight),
                    'When opening, viewer coordinates 0,0 is also image 2 pixel -2*imageWidth, -2*imageHeight');

            var viewerWidth = $(viewer.element).width();
            var viewerHeight = $(viewer.element).height();
            var viewerBottomRight = new OpenSeadragon.Point(viewerWidth, viewerHeight);

            point = viewport.viewerElementToViewportCoordinates(viewerBottomRight);
            pointEqual(point, new OpenSeadragon.Point(1.5, 1.5),
                    'Viewer bottom right has viewport coordinates 1.5,1.5.');
            image1Pixel = tiledImage1.viewerElementToImageCoordinates(viewerBottomRight);
            pointEqual(image1Pixel,
                    new OpenSeadragon.Point(imageWidth * 1.5, imageHeight * 1.5),
                    'Viewer bottom right has image 1 pixel coordinates imageWidth * 1.5, imageHeight * 1.5');
            image2Pixel = tiledImage2.viewerElementToImageCoordinates(viewerBottomRight);
            pointEqual(image2Pixel,
                    new OpenSeadragon.Point(imageWidth, imageHeight),
                    'Viewer bottom right has image 2 pixel coordinates imageWidth,imageHeight.');

            checkPoint(' after opening');
            viewer.addHandler('animation-finish', function animationHandler() {
                viewer.removeHandler('animation-finish', animationHandler);
                checkPoint(' after zoom and pan');
                start();
            });
            viewer.viewport.zoomTo(0.8).panTo(new OpenSeadragon.Point(0.1, 0.2));
        });

        viewer.open([{
                tileSource: "/test/data/testpattern.dzi"
            }, {
                tileSource: "/test/data/testpattern.dzi",
                x: 1,
                y: 1,
                width: 0.5
            }
        ]);
    });

    // ---------
    asyncTest('Multiple images coordinates conversion with viewport rotation', function () {

        viewer.addHandler("open", function () {
            var viewport = viewer.viewport;
            var tiledImage1 = viewer.world.getItemAt(0);
            var tiledImage2 = viewer.world.getItemAt(1);
            var imageWidth = viewer.source.dimensions.x;
            var imageHeight = viewer.source.dimensions.y;

            var viewerWidth = $(viewer.element).width();
            var viewerHeight = $(viewer.element).height();
            var viewerMiddleTop = new OpenSeadragon.Point(viewerWidth / 2, 0);
            var viewerMiddleBottom = new OpenSeadragon.Point(viewerWidth / 2, viewerHeight);

            var point0_0 = new OpenSeadragon.Point(0, 0);
            var point = viewport.viewerElementToViewportCoordinates(viewerMiddleTop);
            pointEqual(point, point0_0, 'When opening, viewer middle top is also viewport 0,0');
            var image1Pixel = tiledImage1.viewerElementToImageCoordinates(viewerMiddleTop);
            pointEqual(image1Pixel, point0_0, 'When opening, viewer middle top is also image 1 pixel 0,0');
            var image2Pixel = tiledImage2.viewerElementToImageCoordinates(viewerMiddleTop);
            pointEqual(image2Pixel,
                    new OpenSeadragon.Point(-2 * imageWidth, -2 * imageHeight),
                    'When opening, viewer middle top is also image 2 pixel -2*imageWidth, -2*imageHeight');

            point = viewport.viewerElementToViewportCoordinates(viewerMiddleBottom);
            pointEqual(point, new OpenSeadragon.Point(1.5, 1.5),
                    'Viewer middle bottom has viewport coordinates 1.5,1.5.');
            image1Pixel = tiledImage1.viewerElementToImageCoordinates(viewerMiddleBottom);
            pointEqual(image1Pixel,
                    new OpenSeadragon.Point(imageWidth * 1.5, imageHeight * 1.5),
                    'Viewer middle bottom has image 1 pixel coordinates imageWidth * 1.5, imageHeight * 1.5');
            image2Pixel = tiledImage2.viewerElementToImageCoordinates(viewerMiddleBottom);
            pointEqual(image2Pixel,
                    new OpenSeadragon.Point(imageWidth, imageHeight),
                    'Viewer middle bottom has image 2 pixel coordinates imageWidth,imageHeight.');

            checkPoint(' after opening');
            viewer.addHandler('animation-finish', function animationHandler() {
                viewer.removeHandler('animation-finish', animationHandler);
                checkPoint(' after zoom and pan');

                //Restore rotation
                viewer.viewport.setRotation(0);
                start();
            });
            viewer.viewport.zoomTo(0.8).panTo(new OpenSeadragon.Point(0.1, 0.2));
        });

        viewer.viewport.setRotation(45);
        viewer.open([{
                tileSource: "/test/data/testpattern.dzi"
            }, {
                tileSource: "/test/data/testpattern.dzi",
                x: 1,
                y: 1,
                width: 0.5
            }
        ]);
    });

    // ----------
    asyncTest('ZoomRatio 1 image', function () {
        viewer.addHandler("open", function () {

            var viewport = viewer.viewport;

            var imageWidth = viewer.source.dimensions.x;

            function getCurrentImageWidth() {
                return viewport.viewportToViewerElementCoordinates(
                        new OpenSeadragon.Point(1, 0)).minus(
                        viewport.viewportToViewerElementCoordinates(
                                new OpenSeadragon.Point(0, 0))).x;
            }

            function checkZoom() {
                var currentImageWidth = getCurrentImageWidth();
                var expectedImageZoom = currentImageWidth / imageWidth;
                var expectedViewportZoom = viewport.getZoom(true);
                var actualImageZoom = viewport.viewportToImageZoom(
                        expectedViewportZoom);
                Util.assessNumericValue(actualImageZoom, expectedImageZoom, precision);

                var actualViewportZoom = viewport.imageToViewportZoom(actualImageZoom);
                Util.assessNumericValue(actualViewportZoom, expectedViewportZoom, precision);
            }

            checkZoom();

            var zoomHandler = function () {
                viewer.removeHandler('animation-finish', zoomHandler);
                checkZoom();
                start();
            };

            viewer.addHandler('animation-finish', zoomHandler);
            viewport.zoomTo(2);
        });

        viewer.open('/test/data/testpattern.dzi');
    });

    // ----------
    asyncTest('ZoomRatio 2 images', function () {
        viewer.addHandler("open", function () {

            var viewport = viewer.viewport;

            var imageWidth = viewer.source.dimensions.x;
            var image1 = viewer.world.getItemAt(0);
            var image2 = viewer.world.getItemAt(1);

            function getCurrentImageWidth(image) {
                var bounds = image.getBounds();
                return viewport.viewportToViewerElementCoordinates(
                        bounds.getTopRight()).minus(
                        viewport.viewportToViewerElementCoordinates(
                                bounds.getTopLeft())).x;
            }

            function checkZoom(image) {
                var currentImageWidth = getCurrentImageWidth(image);
                var expectedImageZoom = currentImageWidth / imageWidth;
                var expectedViewportZoom = viewport.getZoom(true);
                var actualImageZoom = image.viewportToImageZoom(
                        expectedViewportZoom);
                Util.assessNumericValue(actualImageZoom, expectedImageZoom,
                        precision);

                var actualViewportImage1Zoom = image.imageToViewportZoom(actualImageZoom);
                Util.assessNumericValue(
                        actualViewportImage1Zoom, expectedViewportZoom, precision);
            }

            checkZoom(image1);
            checkZoom(image2);

            var zoomHandler = function () {
                viewer.removeHandler('animation-finish', zoomHandler);
                checkZoom(image1);
                checkZoom(image2);
                start();
            };

            viewer.addHandler('animation-finish', zoomHandler);
            viewport.zoomTo(2);
        });

        viewer.open([{
                tileSource: "/test/data/testpattern.dzi"
            }, {
                tileSource: "/test/data/testpattern.dzi",
                x: 1,
                y: 1,
                width: 0.5
            }
        ]);
    });

})();
<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var test = require('tape').test;
var util = require('util');
var common = require('./common');

// --- Globals

// May or not be created by previous test run or whatever else:
var SDC_512 = {
    uuid: '4667d1b8-0bc7-466c-bf62-aae98ba5efa9',
    name: 'sdc_512_ownership',
    version: '1.0.0',
    max_physical_memory: 512,
    quota: 20480,
    max_swap: 1024,
    cpu_cap: 150,
    max_lwps: 2000,
    zfs_io_priority: 10,
    'default': false,
    vcpus: 2,
    active: true,
    owner_uuids: ['b99598ca-d56c-4374-8fdd-32e60f4d1592']
};

var CLIENTS;
var CLIENT;
var SERVER;

// --- Helpers

function checkPackage_6_5(t, pkg) {
    t.ok(pkg, 'Package OK');
    t.ok(pkg.name, 'Package name');
    t.notOk(pkg.id, 'Package has not id');
    t.ok(pkg.memory, 'Package memory');
    t.ok(pkg.disk, 'Package Disk');
    t.ok(!isNaN(pkg.vcpus), 'Package VCPUs OK');
    t.notOk(pkg.version, 'Package has not version');
    t.ok(pkg.swap, 'Package swap');
    t.ok(pkg['default'] !== undefined, 'Package default');
}

function checkPackage_7(t, pkg) {
    t.ok(pkg, 'Package OK');
    t.ok(pkg.name, 'Package name');
    t.ok(pkg.id, 'Package id OK');
    t.ok(pkg.memory, 'Package memory');
    t.ok(pkg.disk, 'Package Disk');
    t.ok(!isNaN(pkg.vcpus), 'Package VCPUs OK');
    t.ok(pkg.version, 'Package version OK');
    t.ok(pkg.swap, 'Package swap');
    t.ok(pkg.lwps, 'Package lwps');
    t.ok(pkg['default'] !== undefined, 'Package default');
}

function searchAndCheck(query, t, checkAttr) {
    CLIENT.get({
        path: '/my/packages?' + query,
        headers: {
            'accept-version': '~7.0'
        }
    }, function (err, req, res, body) {
        t.ifError(err);

        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);

        t.ok(Array.isArray(body));
        t.ok(body.length > 0);

        body.forEach(function (p) {
            checkPackage_7(t, p);
            checkAttr(p);
        });

        t.end();
    });
}

// --- Tests

test('setup', function (t) {
    common.setup(function (_, clients, server) {
        CLIENTS = clients;
        CLIENT  = clients.user;
        SERVER  = server;

        SDC_512.owner_uuids.push(CLIENT.account.uuid);

        common.addPackage(CLIENT, SDC_512, function (err) {
            if (err) {
                throw err;
            }

            t.end();
        });
    });
});

test('ListPackages OK (6.5)', function (t) {
    CLIENT.get({
        path: '/my/packages',
        headers: {
            'accept-version': '~6.5'
        }
    }, function (err, req, res, body) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);
        t.ok(body);
        t.ok(Array.isArray(body));
        t.ok(body.length);
        body.forEach(function (p) {
            checkPackage_6_5(t, p);
        });
        t.end();
    });
});

test('GetPackage OK (6.5)', function (t) {
    CLIENT.get({
        path: '/my/packages/' + SDC_512.name,
        headers: {
            'accept-version': '~6.5'
        }
    }, function (err, req, res, body) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);

        t.deepEqual(body, {
            name:    SDC_512.name,
            memory:  SDC_512.max_physical_memory,
            disk:    SDC_512.quota,
            swap:    SDC_512.max_swap,
            vcpus:   SDC_512.vcpus,
            lwps:    SDC_512.max_lwps,
            default: SDC_512.default
        });

        t.end();
    });
});

test('ListPackages OK (7.0)', function (t) {
    CLIENT.get({
        path: '/my/packages',
        headers: {
            'accept-version': '~7.0'
        }
    }, function (err, req, res, body) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);
        t.ok(body);
        t.ok(Array.isArray(body));
        t.ok(body.length);
        body.forEach(function (p) {
            checkPackage_7(t, p);
        });
        t.end();
    });
});

test('search packages by name (7.0)', function (t) {
    searchAndCheck('name=' + SDC_512.name, t, function (pkg) {
        t.equal(pkg.name, SDC_512.name);
    });
});

test('search packages by memory (7.0)', function (t) {
    searchAndCheck('memory=128', t, function (pkg) {
        t.equal(pkg.memory, 128);
    });
});

test('search packages by disk (7.0)', function (t) {
    searchAndCheck('disk=10240', t, function (pkg) {
        t.equal(pkg.disk, 10240);
    });
});

test('search packages by swap (7.0)', function (t) {
    searchAndCheck('swap=512', t, function (pkg) {
        t.equal(pkg.swap, 512);
    });
});

test('search packages by lwps (7.0)', function (t) {
    searchAndCheck('lwps=2000', t, function (pkg) {
        t.equal(pkg.lwps, 2000);
    });
});

test('search packages by vcpus (7.0)', function (t) {
    searchAndCheck('vcpus=2', t, function (pkg) {
        t.equal(pkg.vcpus, 2);
    });
});

test('search packages by version (7.0)', function (t) {
    searchAndCheck('version=1.0.0', t, function (pkg) {
        t.equal(pkg.version, '1.0.0');
    });
});

test('GetPackage by name OK (7.0)', function (t) {
    CLIENT.get({
        path: '/my/packages/' + SDC_512.name,
        headers: {
            'accept-version': '~7.0'
        }
    }, function (err, req, res, body) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);

        t.deepEqual(body, {
            name:    SDC_512.name,
            memory:  SDC_512.max_physical_memory,
            disk:    SDC_512.quota,
            swap:    SDC_512.max_swap,
            vcpus:   SDC_512.vcpus,
            lwps:    SDC_512.max_lwps,
            default: SDC_512.default,
            id:      SDC_512.uuid,
            version: SDC_512.version
        });

        t.end();
    });
});

test('GetPackage by id OK (7.0)', function (t) {
    CLIENT.get({
        path: '/my/packages/' + SDC_512.uuid,
        headers: {
            'accept-version': '~7.0'
        }
    }, function (err, req, res, body) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);

        t.deepEqual(body, {
            name:    SDC_512.name,
            memory:  SDC_512.max_physical_memory,
            disk:    SDC_512.quota,
            swap:    SDC_512.max_swap,
            vcpus:   SDC_512.vcpus,
            lwps:    SDC_512.max_lwps,
            default: SDC_512.default,
            id:      SDC_512.uuid,
            version: SDC_512.version
        });

        t.end();
    });
});

test('GetPackage 404', function (t) {
    CLIENT.get('/my/packages/' + common.uuid(), function (err) {
        t.ok(err);
        t.equal(err.statusCode, 404);
        t.equal(err.restCode, 'ResourceNotFound');
        t.ok(err.message);
        t.end();
    });
});

test('teardown', function (t) {
    common.deletePackage(CLIENT, SDC_512, function (err) {
        t.ifError(err);

        common.teardown(CLIENTS, SERVER, function () {
            t.end();
        });
    });
});
<commit_msg>PUBAPI-1140 - package tests should search for swap value that's in one of the already-loaded packages.<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var test = require('tape').test;
var util = require('util');
var common = require('./common');

// --- Globals

// May or not be created by previous test run or whatever else:
var SDC_512 = {
    uuid: '4667d1b8-0bc7-466c-bf62-aae98ba5efa9',
    name: 'sdc_512_ownership',
    version: '1.0.0',
    max_physical_memory: 512,
    quota: 20480,
    max_swap: 1024,
    cpu_cap: 150,
    max_lwps: 2000,
    zfs_io_priority: 10,
    'default': false,
    vcpus: 2,
    active: true,
    owner_uuids: ['b99598ca-d56c-4374-8fdd-32e60f4d1592']
};

var CLIENTS;
var CLIENT;
var SERVER;

// --- Helpers

function checkPackage_6_5(t, pkg) {
    t.ok(pkg, 'Package OK');
    t.ok(pkg.name, 'Package name');
    t.notOk(pkg.id, 'Package has not id');
    t.ok(pkg.memory, 'Package memory');
    t.ok(pkg.disk, 'Package Disk');
    t.ok(!isNaN(pkg.vcpus), 'Package VCPUs OK');
    t.notOk(pkg.version, 'Package has not version');
    t.ok(pkg.swap, 'Package swap');
    t.ok(pkg['default'] !== undefined, 'Package default');
}

function checkPackage_7(t, pkg) {
    t.ok(pkg, 'Package OK');
    t.ok(pkg.name, 'Package name');
    t.ok(pkg.id, 'Package id OK');
    t.ok(pkg.memory, 'Package memory');
    t.ok(pkg.disk, 'Package Disk');
    t.ok(!isNaN(pkg.vcpus), 'Package VCPUs OK');
    t.ok(pkg.version, 'Package version OK');
    t.ok(pkg.swap, 'Package swap');
    t.ok(pkg.lwps, 'Package lwps');
    t.ok(pkg['default'] !== undefined, 'Package default');
}

function searchAndCheck(query, t, checkAttr) {
    CLIENT.get({
        path: '/my/packages?' + query,
        headers: {
            'accept-version': '~7.0'
        }
    }, function (err, req, res, body) {
        t.ifError(err);

        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);

        t.ok(Array.isArray(body));
        t.ok(body.length > 0);

        body.forEach(function (p) {
            checkPackage_7(t, p);
            checkAttr(p);
        });

        t.end();
    });
}

// --- Tests

test('setup', function (t) {
    common.setup(function (_, clients, server) {
        CLIENTS = clients;
        CLIENT  = clients.user;
        SERVER  = server;

        SDC_512.owner_uuids.push(CLIENT.account.uuid);

        common.addPackage(CLIENT, SDC_512, function (err) {
            if (err) {
                throw err;
            }

            t.end();
        });
    });
});

test('ListPackages OK (6.5)', function (t) {
    CLIENT.get({
        path: '/my/packages',
        headers: {
            'accept-version': '~6.5'
        }
    }, function (err, req, res, body) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);
        t.ok(body);
        t.ok(Array.isArray(body));
        t.ok(body.length);
        body.forEach(function (p) {
            checkPackage_6_5(t, p);
        });
        t.end();
    });
});

test('GetPackage OK (6.5)', function (t) {
    CLIENT.get({
        path: '/my/packages/' + SDC_512.name,
        headers: {
            'accept-version': '~6.5'
        }
    }, function (err, req, res, body) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);

        t.deepEqual(body, {
            name:    SDC_512.name,
            memory:  SDC_512.max_physical_memory,
            disk:    SDC_512.quota,
            swap:    SDC_512.max_swap,
            vcpus:   SDC_512.vcpus,
            lwps:    SDC_512.max_lwps,
            default: SDC_512.default
        });

        t.end();
    });
});

test('ListPackages OK (7.0)', function (t) {
    CLIENT.get({
        path: '/my/packages',
        headers: {
            'accept-version': '~7.0'
        }
    }, function (err, req, res, body) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);
        t.ok(body);
        t.ok(Array.isArray(body));
        t.ok(body.length);
        body.forEach(function (p) {
            checkPackage_7(t, p);
        });
        t.end();
    });
});

test('search packages by name (7.0)', function (t) {
    searchAndCheck('name=' + SDC_512.name, t, function (pkg) {
        t.equal(pkg.name, SDC_512.name);
    });
});

test('search packages by memory (7.0)', function (t) {
    searchAndCheck('memory=128', t, function (pkg) {
        t.equal(pkg.memory, 128);
    });
});

test('search packages by disk (7.0)', function (t) {
    searchAndCheck('disk=10240', t, function (pkg) {
        t.equal(pkg.disk, 10240);
    });
});

test('search packages by swap (7.0)', function (t) {
    searchAndCheck('swap=256', t, function (pkg) {
        t.equal(pkg.swap, 256);
    });
});

test('search packages by lwps (7.0)', function (t) {
    searchAndCheck('lwps=2000', t, function (pkg) {
        t.equal(pkg.lwps, 2000);
    });
});

test('search packages by vcpus (7.0)', function (t) {
    searchAndCheck('vcpus=2', t, function (pkg) {
        t.equal(pkg.vcpus, 2);
    });
});

test('search packages by version (7.0)', function (t) {
    searchAndCheck('version=1.0.0', t, function (pkg) {
        t.equal(pkg.version, '1.0.0');
    });
});

test('GetPackage by name OK (7.0)', function (t) {
    CLIENT.get({
        path: '/my/packages/' + SDC_512.name,
        headers: {
            'accept-version': '~7.0'
        }
    }, function (err, req, res, body) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);

        t.deepEqual(body, {
            name:    SDC_512.name,
            memory:  SDC_512.max_physical_memory,
            disk:    SDC_512.quota,
            swap:    SDC_512.max_swap,
            vcpus:   SDC_512.vcpus,
            lwps:    SDC_512.max_lwps,
            default: SDC_512.default,
            id:      SDC_512.uuid,
            version: SDC_512.version
        });

        t.end();
    });
});

test('GetPackage by id OK (7.0)', function (t) {
    CLIENT.get({
        path: '/my/packages/' + SDC_512.uuid,
        headers: {
            'accept-version': '~7.0'
        }
    }, function (err, req, res, body) {
        t.ifError(err);
        t.equal(res.statusCode, 200);
        common.checkHeaders(t, res.headers);

        t.deepEqual(body, {
            name:    SDC_512.name,
            memory:  SDC_512.max_physical_memory,
            disk:    SDC_512.quota,
            swap:    SDC_512.max_swap,
            vcpus:   SDC_512.vcpus,
            lwps:    SDC_512.max_lwps,
            default: SDC_512.default,
            id:      SDC_512.uuid,
            version: SDC_512.version
        });

        t.end();
    });
});

test('GetPackage 404', function (t) {
    CLIENT.get('/my/packages/' + common.uuid(), function (err) {
        t.ok(err);
        t.equal(err.statusCode, 404);
        t.equal(err.restCode, 'ResourceNotFound');
        t.ok(err.message);
        t.end();
    });
});

test('teardown', function (t) {
    common.deletePackage(CLIENT, SDC_512, function (err) {
        t.ifError(err);

        common.teardown(CLIENTS, SERVER, function () {
            t.end();
        });
    });
});
<|endoftext|>


<commit_before>var nodeunit = require('nodeunit')
  , MersenneTwister = require('mersennetwister')
  , QDigest  = require('../lib/quantile/q-digest.js')
  , fn = require('../lib/fn.js')
  ;

function actualRankOf(x, ys) {
    var numSmaller = 0;
    var numEqual   = 0;

    ys.forEach(function(y) {
        if (y < x) numSmaller++;
        if (y == x) numEqual++;
    });

    return [
        1.0 * numSmaller / ys.length,
        1.0 * (numSmaller + numEqual) / ys.length
    ];
}

function arraycopy(src, srcPos, dest, destPos, length) {
    for (var i=srcPos, j=destPos; i<length; i++, j++) {
        dest[j] = src[i];
    }
}

exports['qdigest'] = nodeunit.testCase({
    'test comprehensive on mixture': function (test) {
        var r = new MersenneTwister();
        var dists = [
            [100, 50],
            [150, 20],
            [500, 300],
            [10000, 10000]
        ];

        [1, 10, 100, 1000].forEach(function(numSamples) {
            var samples = new Array(dists.length);

            for(var i = 0; i < dists.length; ++i) {
                samples[i] = new Array(numSamples);
                for (var j = 0; j < samples[i].length; ++j) {
                    var num = fn.getRandNormalDistNumber(dists[i][0], dists[i][1], function(){return r.rnd()});
                    samples[i][j] = Math.floor(Math.max(0, num));
                }
            }

            var compressionFactor = 1000;
            var logCapacity = 1;
            var max = 0;

            samples.forEach(function(s) {
                s.forEach(function(x) {
                    max = Math.max(max, x);
                });
            });

            for (var scale = 1; scale < max; scale *= 2, logCapacity++) {
                ;
            }

            var eps = logCapacity / compressionFactor;

            var digests = new Array(dists.length);
            for (var i = 0; i < digests.length; ++i) {
                digests[i] = new QDigest(compressionFactor);

                samples[i].forEach(function(x) {
                    digests[i].offer(x);
                });

                test.equal(samples[i].length, digests[i].computeActualSize());
            }

            var numTotal = 0;
            for (var i = 0; i < digests.length; ++i) {
                for (var q = 0; q <= 1; q += 0.01) {
                    var res = digests[i].getQuantile(q);
                    var actualRank = actualRankOf(res, samples[i]);
                    test.ok(q >= actualRank[0] - eps && q <= actualRank[1] + eps,
                            actualRank[0] + " .. " + actualRank[1] + " outside error bound for  " + q);
                }

                // Test the same on the union of all distributions up to i-th
                numTotal += samples[i].length;
                var total = new Array(numTotal);
                var offset = 0;
                var totalDigest = new QDigest(compressionFactor);
                var expectedSize = 0;
                for (var j = 0; j <= i; ++j) {
                    arraycopy(samples[j], 0, total, offset, samples[j].length);
                    offset += samples[j].length;
                    totalDigest = QDigest.unionOf(totalDigest, digests[j]);
                    expectedSize += samples[j].length;
                }

                test.equal(expectedSize, totalDigest.computeActualSize());

                for (var q = 0; q <= 1; q += 0.01) {
                    var res = totalDigest.getQuantile(q);
                    var actualRank = actualRankOf(res, total);
                    test.ok(q >= actualRank[0] - eps && q <= actualRank[1] + eps,
                            actualRank[0] + " .. " + actualRank[1] + " outside error bound for  " + q);
                }
            }
        });

        test.done();
    }
});
<commit_msg>added q-digest merge test<commit_after>var nodeunit = require('nodeunit')
  , MersenneTwister = require('mersennetwister')
  , QDigest  = require('../lib/quantile/q-digest.js')
  , fn = require('../lib/fn.js')
  ;

function actualRankOf(x, ys) {
    var numSmaller = 0;
    var numEqual   = 0;

    ys.forEach(function(y) {
        if (y < x) numSmaller++;
        if (y == x) numEqual++;
    });

    return [
        1.0 * numSmaller / ys.length,
        1.0 * (numSmaller + numEqual) / ys.length
    ];
}

function arraycopy(src, srcPos, dest, destPos, length) {
    for (var i=srcPos, j=destPos; i<length; i++, j++) {
        dest[j] = src[i];
    }
}

exports['qdigest'] = nodeunit.testCase({
    'test comprehensive on mixture': function (test) {
        var r = new MersenneTwister();
        var dists = [
            [100, 50],
            [150, 20],
            [500, 300],
            [10000, 10000]
        ];

        [1, 10, 100, 1000].forEach(function(numSamples) {
            var samples = new Array(dists.length);

            for(var i = 0; i < dists.length; ++i) {
                samples[i] = new Array(numSamples);
                for (var j = 0; j < samples[i].length; ++j) {
                    var num = fn.getRandNormalDistNumber(dists[i][0], dists[i][1], function(){return r.rnd()});
                    samples[i][j] = Math.floor(Math.max(0, num));
                }
            }

            var compressionFactor = 1000;
            var logCapacity = 1;
            var max = 0;

            samples.forEach(function(s) {
                s.forEach(function(x) {
                    max = Math.max(max, x);
                });
            });

            for (var scale = 1; scale < max; scale *= 2, logCapacity++) {
                ;
            }

            var eps = logCapacity / compressionFactor;

            var digests = new Array(dists.length);
            for (var i = 0; i < digests.length; ++i) {
                digests[i] = new QDigest(compressionFactor);

                samples[i].forEach(function(x) {
                    digests[i].offer(x);
                });

                test.equal(samples[i].length, digests[i].computeActualSize());
            }

            var numTotal = 0;
            for (var i = 0; i < digests.length; ++i) {
                for (var q = 0; q <= 1; q += 0.01) {
                    var res = digests[i].getQuantile(q);
                    var actualRank = actualRankOf(res, samples[i]);
                    test.ok(q >= actualRank[0] - eps && q <= actualRank[1] + eps,
                            actualRank[0] + " .. " + actualRank[1] + " outside error bound for  " + q);
                }

                // Test the same on the union of all distributions up to i-th
                numTotal += samples[i].length;
                var total = new Array(numTotal);
                var offset = 0;
                var totalDigest = new QDigest(compressionFactor);
                var expectedSize = 0;
                for (var j = 0; j <= i; ++j) {
                    arraycopy(samples[j], 0, total, offset, samples[j].length);
                    offset += samples[j].length;
                    totalDigest = QDigest.unionOf(totalDigest, digests[j]);
                    expectedSize += samples[j].length;
                }

                test.equal(expectedSize, totalDigest.computeActualSize());

                for (var q = 0; q <= 1; q += 0.01) {
                    var res = totalDigest.getQuantile(q);
                    var actualRank = actualRankOf(res, total);
                    test.ok(q >= actualRank[0] - eps && q <= actualRank[1] + eps,
                            actualRank[0] + " .. " + actualRank[1] + " outside error bound for  " + q);
                }
            }
        });

        test.done();
    },

    'test merge': function (test) {
        var compressionFactor = 2;

        var aSamples = [0,0,1,0,1,1];
        var bSamples = [0,1,0,0,0,3];
        var allSamples = aSamples.concat(bSamples);

        var a = new QDigest(compressionFactor);
        var b = new QDigest(compressionFactor);
        var c = new QDigest(compressionFactor);

        aSamples.forEach(function(x) {
            a.offer(x);
        });

        bSamples.forEach(function(x) {
            b.offer(x);
        });

        allSamples.forEach(function(x) {
            c.offer(x);
        });

        var ab = QDigest.unionOf(a, b);

        test.equal(allSamples.length, c.computeActualSize());

        var logCapacity = 1;
        var max = 0;

        allSamples.forEach(function(x) {
            max = Math.max(max, x);
        });

        for (var scale = 1; scale < max; scale *= compressionFactor, logCapacity++) {}

        var eps = logCapacity / compressionFactor;
        for (var q = 0; q <= 1; q += 0.01)
        {
            var res = c.getQuantile(q);
            var actualRank = actualRankOf(res, allSamples);
            test.ok(q >= actualRank[0] - eps && q <= actualRank[1] + eps,
                    actualRank[0] + " .. " + actualRank[1] + " outside error bound for  " + q);
        }

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


<commit_before>describe("sampletest", function () {
  it("", function () {
    var React = require('react');
    var Kinetic = require('kinetic');
    var ReactKinetic = require('../react-kinetic');
    expect(true).toBe(true);
  });
});
<commit_msg>Added simple tests for Circle, Text and TextPath rendering. Text and TextPath are not currently working.<commit_after>var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var RK = require('../react-kinetic');

describe('Stage', function () {
  it('can render empty Stage', function () {
    var stage = TestUtils.renderIntoDocument(RK.Stage(null));
    expect(stage.getDOMNode().textContent).toEqual('');
  });
});

function renderSingle(type, component) {
  var stage = TestUtils.renderIntoDocument(
    RK.Stage(null,
      RK.Layer(null, component)));
  return TestUtils.findRenderedComponentWithType(stage, type);
}

describe('Circle', function () {
  it('can render Circle', function () {
    var rendered = renderSingle(RK.Circle, RK.Circle({x: 10, y: 20, radius: 5, stroke: 'red'}));
    expect(rendered.props.x).toBe(10);
    expect(rendered.props.y).toBe(20);
    expect(rendered.props.radius).toBe(5);
  });
});

describe('Text', function () {
  it('can render Text with no size', function () {
    var rendered = renderSingle(RK.Text, RK.Text(null, "Hello, world"));
    expect(rendered.getDOMNode().textContent).toEqual('Hello, world');
  });
  it('can render Text with size', function () {
    var rendered = renderSingle(RK.Text, RK.Text({
      x: 10,
      y: 15,
      text: 'Simple Text',
      fontSize: 30,
      fontFamily: 'Calibri',
      fill: 'green'
    }, "Hello, world"));
    expect(rendered.getDOMNode().textContent).toEqual('Hello, world');
  });
});

describe('TextPath', function () {
  it('can render TextPath', function () {
    var txt = 'All the world\'s a stage, and all the men and women merely players.';
    var rendered = renderSingle(RK.TextPath, RK.TextPath({
      x: 100,
      y: 50,
      fill: '#333',
      fontSize: '24',
      fontFamily: 'Arial',
      text: txt,
      data: 'M10,10 C0,0 10,150 100,100 S300,150 400,50'
    }));
    expect(rendered.props.text).toBe(txt);
  });
});
<|endoftext|>


<commit_before>'use strict';
const url = require('url');
const qs = require('querystring');
const util = require('util');

const MongoClient = require('../../lib/mongo_client');
const TopologyType = require('../../lib/core/sdam/topology_description').TopologyType;
const core = require('../../lib/core');

class NativeConfiguration {
  constructor(parsedURI, context) {
    this.topologyType = context.topologyType;
    this.options = Object.assign(
      {
        hosts: parsedURI.hosts,
        host: parsedURI.hosts[0] ? parsedURI.hosts[0].host : 'localhost',
        port: parsedURI.hosts[0] ? parsedURI.hosts[0].port : 27017,
        db: parsedURI.auth && parsedURI.auth.db ? parsedURI.auth.db : 'integration_tests'
      },
      parsedURI.options
    );

    this.mongo = this.require = require('../..');
    this.writeConcern = function() {
      return { w: 1 };
    };
  }

  get host() {
    return this.options.host;
  }

  get port() {
    return this.options.port;
  }

  set db(_db) {
    this.options.db = _db;
  }

  get db() {
    return this.options.db;
  }

  // legacy accessors, consider for removal
  get replicasetName() {
    return this.options.replicaSet;
  }

  get setName() {
    return this.options.replicaSet;
  }

  usingUnifiedTopology() {
    return !!process.env.MONGODB_UNIFIED_TOPOLOGY;
  }

  newClient(dbOptions, serverOptions) {
    if (typeof dbOptions === 'string') {
      return new MongoClient(
        dbOptions,
        this.usingUnifiedTopology()
          ? Object.assign({ useUnifiedTopology: true }, serverOptions)
          : serverOptions
      );
    }

    // support MongoClient contructor form (url, options) for `newClient`
    if (typeof dbOptions === 'string') {
      return new MongoClient(
        dbOptions,
        this.usingUnifiedTopology()
          ? Object.assign({ useUnifiedTopology: true }, serverOptions)
          : serverOptions
      );
    }

    dbOptions = dbOptions || {};
    serverOptions = Object.assign({}, { haInterval: 100 }, serverOptions);
    if (this.usingUnifiedTopology()) {
      serverOptions.useUnifiedTopology = true;
    }

    // Fall back
    let dbHost = (serverOptions && serverOptions.host) || this.options.host;
    const dbPort = (serverOptions && serverOptions.port) || this.options.port;
    if (dbHost.indexOf('.sock') !== -1) {
      dbHost = qs.escape(dbHost);
    }

    if (this.options.replicaSet) {
      Object.assign(dbOptions, { replicaSet: this.options.replicaSet, auto_reconnect: false });
    }

    const connectionString = url.format({
      protocol: 'mongodb',
      slashes: true,
      hostname: dbHost,
      port: dbPort,
      query: dbOptions,
      pathname: '/'
    });

    return new MongoClient(connectionString, serverOptions);
  }

  newTopology(host, port, options) {
    options = Object.assign({}, options);
    host = host || this.options.host;
    port = port || this.options.port;

    if (this.usingUnifiedTopology()) {
      return new core.Topology([{ host, port }], options);
    }

    if (this.topologyType === TopologyType.ReplicaSetWithPrimary) {
      options.poolSize = 1;
      options.autoReconnect = false;
      return new core.ReplSet([{ host, port }], options);
    }

    if (this.topologyType === TopologyType.Sharded) {
      return new core.Mongos([{ host, port }], options);
    }

    return new core.Server(Object.assign({ host, port }, options));
  }

  url(username, password) {
    const query = {};
    if (this.options.replicaSet) {
      Object.assign(query, { replicaSet: this.options.replicaSet, auto_reconnect: false });
    }

    let multipleHosts;
    if (this.options.hosts.length > 1) {
      multipleHosts = this.options.hosts
        .reduce((built, host) => {
          built.push(`${host.host}:${host.port}`);
          return built;
        }, [])
        .join(',');
    }

    const urlObject = {
      protocol: 'mongodb',
      slashes: true,
      pathname: `/${this.options.db}`,
      query
    };

    if (multipleHosts) {
      Object.assign(urlObject, { hostname: '%s' });
    } else {
      Object.assign(urlObject, {
        hostname: this.options.host,
        port: this.options.port
      });
    }

    if (username || password) {
      urlObject.auth = password == null ? username : `${username}:${password}`;
    }

    if (multipleHosts) {
      return util.format(url.format(urlObject), multipleHosts);
    }

    return url.format(urlObject);
  }

  writeConcernMax() {
    if (this.topologyType !== TopologyType.Single) {
      return { w: 'majority', wtimeout: 30000 };
    }

    return { w: 1 };
  }

  // server37631Workaround() {
  //   console.log('[applying SERVER-37631 workaround]');
  //   const configServers = this.manager.configurationServers.managers;
  //   const proxies = this.manager.proxies;
  //   const configServersPromise = configServers.reduce((result, server) => {
  //     return result.then(() =>
  //       server.executeCommand('admin.$cmd', { refreshLogicalSessionCacheNow: 1 })
  //     );
  //   }, Promise.resolve());

  //   return configServersPromise.then(() => {
  //     return proxies.reduce((promise, proxy) => {
  //       return promise.then(() =>
  //         proxy.executeCommand('admin.$cmd', { refreshLogicalSessionCacheNow: 1 })
  //       );
  //     }, Promise.resolve());
  //   });
  // }
}

module.exports = NativeConfiguration;
<commit_msg>test: support multiple hosts for topology factory method<commit_after>'use strict';
const url = require('url');
const qs = require('querystring');
const util = require('util');

const MongoClient = require('../../lib/mongo_client');
const TopologyType = require('../../lib/core/sdam/topology_description').TopologyType;
const core = require('../../lib/core');

class NativeConfiguration {
  constructor(parsedURI, context) {
    this.topologyType = context.topologyType;
    this.options = Object.assign(
      {
        hosts: parsedURI.hosts,
        host: parsedURI.hosts[0] ? parsedURI.hosts[0].host : 'localhost',
        port: parsedURI.hosts[0] ? parsedURI.hosts[0].port : 27017,
        db: parsedURI.auth && parsedURI.auth.db ? parsedURI.auth.db : 'integration_tests'
      },
      parsedURI.options
    );

    this.mongo = this.require = require('../..');
    this.writeConcern = function() {
      return { w: 1 };
    };
  }

  get host() {
    return this.options.host;
  }

  get port() {
    return this.options.port;
  }

  set db(_db) {
    this.options.db = _db;
  }

  get db() {
    return this.options.db;
  }

  // legacy accessors, consider for removal
  get replicasetName() {
    return this.options.replicaSet;
  }

  get setName() {
    return this.options.replicaSet;
  }

  usingUnifiedTopology() {
    return !!process.env.MONGODB_UNIFIED_TOPOLOGY;
  }

  newClient(dbOptions, serverOptions) {
    if (typeof dbOptions === 'string') {
      return new MongoClient(
        dbOptions,
        this.usingUnifiedTopology()
          ? Object.assign({ useUnifiedTopology: true }, serverOptions)
          : serverOptions
      );
    }

    // support MongoClient contructor form (url, options) for `newClient`
    if (typeof dbOptions === 'string') {
      return new MongoClient(
        dbOptions,
        this.usingUnifiedTopology()
          ? Object.assign({ useUnifiedTopology: true }, serverOptions)
          : serverOptions
      );
    }

    dbOptions = dbOptions || {};
    serverOptions = Object.assign({}, { haInterval: 100 }, serverOptions);
    if (this.usingUnifiedTopology()) {
      serverOptions.useUnifiedTopology = true;
    }

    // Fall back
    let dbHost = (serverOptions && serverOptions.host) || this.options.host;
    const dbPort = (serverOptions && serverOptions.port) || this.options.port;
    if (dbHost.indexOf('.sock') !== -1) {
      dbHost = qs.escape(dbHost);
    }

    if (this.options.replicaSet) {
      Object.assign(dbOptions, { replicaSet: this.options.replicaSet, auto_reconnect: false });
    }

    const connectionString = url.format({
      protocol: 'mongodb',
      slashes: true,
      hostname: dbHost,
      port: dbPort,
      query: dbOptions,
      pathname: '/'
    });

    return new MongoClient(connectionString, serverOptions);
  }

  newTopology(host, port, options) {
    options = Object.assign({}, options);
    host = host || this.options.host;
    port = port || this.options.port;

    let hosts = [{ host, port }];
    if (this.options.hosts) {
      hosts = hosts.concat(this.options.hosts);
    }

    if (this.usingUnifiedTopology()) {
      return new core.Topology(hosts, options);
    }

    if (this.topologyType === TopologyType.ReplicaSetWithPrimary) {
      options.poolSize = 1;
      options.autoReconnect = false;
      return new core.ReplSet(hosts, options);
    }

    if (this.topologyType === TopologyType.Sharded) {
      return new core.Mongos(hosts, options);
    }

    return new core.Server(Object.assign({ host, port }, options));
  }

  url(username, password) {
    const query = {};
    if (this.options.replicaSet) {
      Object.assign(query, { replicaSet: this.options.replicaSet, auto_reconnect: false });
    }

    let multipleHosts;
    if (this.options.hosts.length > 1) {
      multipleHosts = this.options.hosts
        .reduce((built, host) => {
          built.push(`${host.host}:${host.port}`);
          return built;
        }, [])
        .join(',');
    }

    const urlObject = {
      protocol: 'mongodb',
      slashes: true,
      pathname: `/${this.options.db}`,
      query
    };

    if (multipleHosts) {
      Object.assign(urlObject, { hostname: '%s' });
    } else {
      Object.assign(urlObject, {
        hostname: this.options.host,
        port: this.options.port
      });
    }

    if (username || password) {
      urlObject.auth = password == null ? username : `${username}:${password}`;
    }

    if (multipleHosts) {
      return util.format(url.format(urlObject), multipleHosts);
    }

    return url.format(urlObject);
  }

  writeConcernMax() {
    if (this.topologyType !== TopologyType.Single) {
      return { w: 'majority', wtimeout: 30000 };
    }

    return { w: 1 };
  }

  // server37631Workaround() {
  //   console.log('[applying SERVER-37631 workaround]');
  //   const configServers = this.manager.configurationServers.managers;
  //   const proxies = this.manager.proxies;
  //   const configServersPromise = configServers.reduce((result, server) => {
  //     return result.then(() =>
  //       server.executeCommand('admin.$cmd', { refreshLogicalSessionCacheNow: 1 })
  //     );
  //   }, Promise.resolve());

  //   return configServersPromise.then(() => {
  //     return proxies.reduce((promise, proxy) => {
  //       return promise.then(() =>
  //         proxy.executeCommand('admin.$cmd', { refreshLogicalSessionCacheNow: 1 })
  //       );
  //     }, Promise.resolve());
  //   });
  // }
}

module.exports = NativeConfiguration;
<|endoftext|>


<commit_before>var chai = require('chai');
var Strategy = require('../lib/strategy');

describe('Strategy', function() {

  var strategy = new Strategy(function(token, cb) {
    throw new Error('verify function should not be called');
  });

  it('should be named bearer', function() {
    expect(strategy.name).to.equal('bearer');
  });

  it('should challenge request without credentials', function(done) {
    chai.passport.use(strategy)
      .fail(function(challenge, status) {
        expect(challenge).to.equal('Bearer realm="Users"');
        expect(status).to.be.undefined;
        done();
      })
      .authenticate();
  });

  it('should challenge request with non-bearer scheme', function(done) {
    chai.passport.use(strategy)
      .request(function(req) {
        req.headers['authorization'] = 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==';
      })
      .fail(function(challenge, status) {
        expect(challenge).to.equal('Bearer realm="Users"');
        expect(status).to.be.undefined;
        done();
      })
      .authenticate();
  });

  it('should challenge request with scheme name differing by suffix', function(done) {
    chai.passport.use(strategy)
      .request(function(req) {
        req.headers['authorization'] = 'Bearer2 mF_9.B5f-4.1JqM';
      })
      .fail(function(challenge, status) {
        expect(challenge).to.equal('Bearer realm="Users"');
        expect(status).to.be.undefined;
        done();
      })
      .authenticate();
  });

  it('should challenge request with scheme name differing by prefix', function(done) {
    chai.passport.use(strategy)
      .request(function(req) {
        req.headers['authorization'] = 'XBearer mF_9.B5f-4.1JqM';
      })
      .fail(function(challenge, status) {
        expect(challenge).to.equal('Bearer realm="Users"');
        expect(status).to.be.undefined;
        done();
      })
      .authenticate();
  });

  it('should refuse request with token transmitted in more than one method', function(done) {
    chai.passport.use(strategy)
      .fail(function(status) {
        expect(status).to.equal(400);
        done();
      })
      .request(function(req) {
        req.headers['authorization'] = 'Bearer mF_9.B5f-4.1JqM';
        req.query = {};
        req.query.access_token = 'mF_9.B5f-4.1JqM';
      })
      .authenticate();
  });

  it('should refuse request with malformed authorization header', function(done) {
    chai.passport.use(strategy)
      .request(function(req) {
        req.headers['authorization'] = 'Bearer';
      })
      .fail(function(status) {
        expect(status).to.equal(400);
        done();
      })
      .authenticate();
  });

  describe('with realm option', function() {

    it('should challenge request with realm', function(done) {
      var strategy = new Strategy({ realm: 'example' }, function(token, cb) {
        throw new Error('verify function should not be called');
      });

      chai.passport.use(strategy)
        .fail(function(challenge, status) {
          expect(challenge).to.equal('Bearer realm="example"');
          expect(status).to.be.undefined;
          done();
        })
        .authenticate();
    });

  }); // with realm option

  describe('with scope option', function() {

    it('should challenge request with scope as array', function(done) {
      var strategy = new Strategy({ scope: ['profile', 'email']  }, function(token, cb) {
        throw new Error('verify function should not be called');
      });

      chai.passport.use(strategy)
        .fail(function(challenge, status) {
          expect(challenge).to.equal('Bearer realm="Users", scope="profile email"');
          expect(status).to.be.undefined;
          done();
        })
        .authenticate();
    });

    it('should challenge request with scope as string', function(done) {
      var strategy = new Strategy({ scope: 'profile' }, function(token, cb) {
        throw new Error('verify function should not be called');
      });

      chai.passport.use(strategy)
        .fail(function(challenge, status) {
          expect(challenge).to.equal('Bearer realm="Users", scope="profile"');
          expect(status).to.be.undefined;
          done();
        })
        .authenticate();
    });

  }); // with scope option

  it('should throw if constructed without a verify callback', function() {
    expect(function() {
      new Strategy();
    }).to.throw(TypeError, 'HTTPBearerStrategy requires a verify callback');
  });

});
<commit_msg>Update test name.<commit_after>var chai = require('chai');
var Strategy = require('../lib/strategy');

describe('Strategy', function() {

  var strategy = new Strategy(function(token, cb) {
    throw new Error('verify function should not be called');
  });

  it('should be named bearer', function() {
    expect(strategy.name).to.equal('bearer');
  });

  it('should challenge request without credentials', function(done) {
    chai.passport.use(strategy)
      .fail(function(challenge, status) {
        expect(challenge).to.equal('Bearer realm="Users"');
        expect(status).to.be.undefined;
        done();
      })
      .authenticate();
  });

  it('should challenge request with non-bearer scheme', function(done) {
    chai.passport.use(strategy)
      .request(function(req) {
        req.headers['authorization'] = 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==';
      })
      .fail(function(challenge, status) {
        expect(challenge).to.equal('Bearer realm="Users"');
        expect(status).to.be.undefined;
        done();
      })
      .authenticate();
  });

  it('should challenge request with scheme name differing by suffix', function(done) {
    chai.passport.use(strategy)
      .request(function(req) {
        req.headers['authorization'] = 'Bearer2 mF_9.B5f-4.1JqM';
      })
      .fail(function(challenge, status) {
        expect(challenge).to.equal('Bearer realm="Users"');
        expect(status).to.be.undefined;
        done();
      })
      .authenticate();
  });

  it('should challenge request with scheme name differing by prefix', function(done) {
    chai.passport.use(strategy)
      .request(function(req) {
        req.headers['authorization'] = 'XBearer mF_9.B5f-4.1JqM';
      })
      .fail(function(challenge, status) {
        expect(challenge).to.equal('Bearer realm="Users"');
        expect(status).to.be.undefined;
        done();
      })
      .authenticate();
  });

  it('should refuse request with token transmitted in more than one method', function(done) {
    chai.passport.use(strategy)
      .fail(function(status) {
        expect(status).to.equal(400);
        done();
      })
      .request(function(req) {
        req.headers['authorization'] = 'Bearer mF_9.B5f-4.1JqM';
        req.query = {};
        req.query.access_token = 'mF_9.B5f-4.1JqM';
      })
      .authenticate();
  });

  it('should refuse request with malformed header field', function(done) {
    chai.passport.use(strategy)
      .request(function(req) {
        req.headers['authorization'] = 'Bearer';
      })
      .fail(function(status) {
        expect(status).to.equal(400);
        done();
      })
      .authenticate();
  });

  describe('with realm option', function() {

    it('should challenge request with realm', function(done) {
      var strategy = new Strategy({ realm: 'example' }, function(token, cb) {
        throw new Error('verify function should not be called');
      });

      chai.passport.use(strategy)
        .fail(function(challenge, status) {
          expect(challenge).to.equal('Bearer realm="example"');
          expect(status).to.be.undefined;
          done();
        })
        .authenticate();
    });

  }); // with realm option

  describe('with scope option', function() {

    it('should challenge request with scope as array', function(done) {
      var strategy = new Strategy({ scope: ['profile', 'email']  }, function(token, cb) {
        throw new Error('verify function should not be called');
      });

      chai.passport.use(strategy)
        .fail(function(challenge, status) {
          expect(challenge).to.equal('Bearer realm="Users", scope="profile email"');
          expect(status).to.be.undefined;
          done();
        })
        .authenticate();
    });

    it('should challenge request with scope as string', function(done) {
      var strategy = new Strategy({ scope: 'profile' }, function(token, cb) {
        throw new Error('verify function should not be called');
      });

      chai.passport.use(strategy)
        .fail(function(challenge, status) {
          expect(challenge).to.equal('Bearer realm="Users", scope="profile"');
          expect(status).to.be.undefined;
          done();
        })
        .authenticate();
    });

  }); // with scope option

  it('should throw if constructed without a verify callback', function() {
    expect(function() {
      new Strategy();
    }).to.throw(TypeError, 'HTTPBearerStrategy requires a verify callback');
  });

});
<|endoftext|>


<commit_before>import EventEmitter from 'events';

import MessengerClient from './messenger-client';

import MessengerText from './elements/messenger-text';
import MessengerImage from './elements/messenger-image';
import MessengerButton from './elements/messenger-button';
import MessengerBubble from './elements/messenger-bubble';
import MessengerAddress from './elements/messenger-address';
import MessengerSummary from './elements/messenger-summary';
import MessengerAdjustment from './elements/messenger-adjustment';

import MessengerButtonTemplate from './templates/messenger-button-template';
import MessengerGenericTemplate from './templates/messenger-generic-template';
import MessengerReceiptTemplate from './templates/messenger-receipt-template';

class MessengerWrapper extends EventEmitter {
  constructor(opts) {
    super();

    opts = opts || {};

    if (!opts.verifyToken || !opts.pageAccessToken) {
      throw new Error('VERIFY_TOKEN or PAGE_ACCESS_TOKEN are missing.');
    }

    this.verifyToken = opts.verifyToken;
    this.pageAccessToken = opts.pageAccessToken;
    this.messengerClient = new MessengerClient(this);
    this.lastEntry = {};
  }

  verify(req, res) {
    if (req.query['hub.verify_token'] === this.verifyToken) {
      return res.send(req.query['hub.challenge']);
    } else {
      return res.send('VERIFY_TOKEN does not match.');
    }
  }

  handle(req) {
    let entries = req.body.entry;

    entries.forEach((entry) => {
      entry.messaging.forEach((event) => {
        if (event.message) {
          this.handleEvent('message', event);
        }
        else if (event.delivery) {
          this.handleEvent('delivery', event);
        }
        else if (event.postback) {
          this.handleEvent('postback', event);
        }
      });
    });
  }

  handleEvent(action, event) {
    this.lastEntry = event;
    this.emit(action, event);
  }

  getUser() {
    return this.messengerClient.getUserData(this.lastEntry);
  }

  send(payload) {
    return this.messengerClient.sendData(payload, this.lastEntry);
  }

  getUserId() {
    return this.lastEntry.sender.id;
  }

  subscribe() {
    return this.messengerClient.subscribeAppToPage();
  }
}

export {
  MessengerWrapper,
  MessengerText,
  MessengerImage,
  MessengerButton,
  MessengerBubble,
  MessengerAddress,
  MessengerSummary,
  MessengerAdjustment,
  MessengerButtonTemplate,
  MessengerGenericTemplate,
  MessengerReceiptTemplate
}
<commit_msg>messenger-wrapper: handle optin event<commit_after>import EventEmitter from 'events';

import MessengerClient from './messenger-client';

import MessengerText from './elements/messenger-text';
import MessengerImage from './elements/messenger-image';
import MessengerButton from './elements/messenger-button';
import MessengerBubble from './elements/messenger-bubble';
import MessengerAddress from './elements/messenger-address';
import MessengerSummary from './elements/messenger-summary';
import MessengerAdjustment from './elements/messenger-adjustment';

import MessengerButtonTemplate from './templates/messenger-button-template';
import MessengerGenericTemplate from './templates/messenger-generic-template';
import MessengerReceiptTemplate from './templates/messenger-receipt-template';

class MessengerWrapper extends EventEmitter {
  constructor(opts) {
    super();

    opts = opts || {};

    if (!opts.verifyToken || !opts.pageAccessToken) {
      throw new Error('VERIFY_TOKEN or PAGE_ACCESS_TOKEN are missing.');
    }

    this.verifyToken = opts.verifyToken;
    this.pageAccessToken = opts.pageAccessToken;
    this.messengerClient = new MessengerClient(this);
    this.lastEntry = {};
  }

  verify(req, res) {
    if (req.query['hub.verify_token'] === this.verifyToken) {
      return res.send(req.query['hub.challenge']);
    } else {
      return res.send('VERIFY_TOKEN does not match.');
    }
  }

  handle(req) {
    let entries = req.body.entry;

    entries.forEach((entry) => {
      entry.messaging.forEach((event) => {
        if (event.message) {
          this.handleEvent('message', event);
        }
        else if (event.delivery) {
          this.handleEvent('delivery', event);
        }
        else if (event.postback) {
          this.handleEvent('postback', event);
        }
        else if (event.optin) {
          this.handleEvent('optin', event);
        }
      });
    });
  }

  handleEvent(action, event) {
    this.lastEntry = event;
    this.emit(action, event);
  }

  getUser() {
    return this.messengerClient.getUserData(this.lastEntry);
  }

  send(payload) {
    return this.messengerClient.sendData(payload, this.lastEntry);
  }

  getUserId() {
    return this.lastEntry.sender.id;
  }

  subscribe() {
    return this.messengerClient.subscribeAppToPage();
  }
}

export {
  MessengerWrapper,
  MessengerText,
  MessengerImage,
  MessengerButton,
  MessengerBubble,
  MessengerAddress,
  MessengerSummary,
  MessengerAdjustment,
  MessengerButtonTemplate,
  MessengerGenericTemplate,
  MessengerReceiptTemplate
}
<|endoftext|>


<commit_before>'use strict';

module.exports = function(runtime, stdout){

  var path = require('path');

  stdout.enable();
  it('config props [env, argv, parse, timer, name]', function(){

    console.log(runtime.config())
    runtime.config().should.have
      .properties('env', 'parse', 'timer', 'name');
  });

  it('env props [cwd, gulpfile, cliPackage, modulePackage]', function(){

    runtime.config().env.should.have
      .properties('INIT_CWD', 'gulpfile', 'cliPackage', 'modulePackage');
  });

  /*
   * Note: make better tests for this
   */
  it('env.gulpfile if is defined, matches the required file', function(){

    var gulpfile = runtime.config().argv;

    if( gulpfile ){
      gulpfile.should.be
        .a.String.and.be.exactly(
          require.resolve(path.resolve('.', 'gulpfile'))
        );
    } else {
      (gulpfile === void 0).should.be.true;
    }

  });

};
<commit_msg>remove console.log from _config.js tests<commit_after>'use strict';

module.exports = function(runtime, stdout){

  var path = require('path');

  stdout.enable();
  it('config props [env, argv, parse, timer, name]', function(){

    runtime.config().should.have
      .properties('env', 'parse', 'timer', 'name');
  });

  it('env props [cwd, gulpfile, cliPackage, modulePackage]', function(){

    runtime.config().env.should.have
      .properties('INIT_CWD', 'gulpfile', 'cliPackage', 'modulePackage');
  });

  /*
   * Note: make better tests for this
   */
  it('env.gulpfile if is defined, matches the required file', function(){

    var gulpfile = runtime.config().argv;

    if( gulpfile ){
      gulpfile.should.be
        .a.String.and.be.exactly(
          require.resolve(path.resolve('.', 'gulpfile'))
        );
    } else {
      (gulpfile === void 0).should.be.true;
    }

  });

};
<|endoftext|>