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

var loopback = require('loopback');

var app = loopback();
var loopbackJsonSchema = require('../../../index');
var JsonSchema = require('../../../models/json-schema');

describe('JsonSchema', function() {
    beforeEach(function() {
        loopbackJsonSchema.initLoopbackJsonSchema(app);
    });

    describe('.create', function() {
        it('should set $schema', function() {
            JsonSchema.create({modelName: 'test'}, function(_, jsonSchema) {
                expect(jsonSchema.$schema).to.exist;
            });
        });

        it('should create model defined by the json schema provided', function() {
            JsonSchema.create({modelName: 'test'}, function() {
                expect(loopback.getModel('test')).to.exist;
            });
        });
    });

    describe('.registerLoopbackModelForCollection', function() {
        it('should register loopback model for an existing collection JSON schema', function(done) {
            var jsonSchema = JsonSchema.create({ modelName: 'person', collectionName: 'people' });

            var next = function() {
                var Person = loopback.getModel('person');
                expect(Person).to.not.be.null;
                expect(Person.definition.name).to.equal("person");
                expect(Person.definition.settings.plural).to.equal("people");
                done();
            };
            JsonSchema.registerLoopbackModelForCollection("people", app, next);

            JsonSchema.remove({ modelName: 'person' });
        });

        it('should log when collection JSON schema was not found', function(done) {
            var log = sinon.stub(console, "warn");
            var next = function() {
                expect(log).to.have.been.calledWith("JSON Schema for collectionName:", "people", "Not found.");
                done();
            };

            JsonSchema.registerLoopbackModelForCollection("people", app, next);
        });

        xit('should log error when some problem happened with the JSON schema query', function() {
            // simulate error and assert log has been called
        });
    });
});
<commit_msg>Move #createLoopbackModel test to integration test.<commit_after>var expect = require('chai').expect;
var sinon = require('sinon');

var loopback = require('loopback');

var app = loopback();
var loopbackJsonSchema = require('../../../index');
var JsonSchema = require('../../../models/json-schema');

describe('JsonSchema', function() {
    beforeEach(function() {
        loopbackJsonSchema.initLoopbackJsonSchema(app);
    });

    describe('.create', function() {
        it('should set $schema', function() {
            JsonSchema.create({modelName: 'test'}, function(_, jsonSchema) {
                expect(jsonSchema.$schema).to.exist;
            });
        });

        it('should create model defined by the json schema provided', function() {
            JsonSchema.create({modelName: 'test'}, function() {
                expect(loopback.getModel('test')).to.exist;
            });
        });
    });

    describe('#createLoopbackModel', function() {
        var Test;

        beforeEach(function() {
            var jsonSchema = new JsonSchema({modelName: 'test', collectionName: 'testplural'});
            jsonSchema.createLoopbackModel(app);
            Test = loopback.getModel('test');
        });

        it('should create model defined by this json schema', function() {
            expect(Test).to.exist;
        });

        it("should use collectionName as model's plural", function() {
            expect(Test.pluralModelName).to.equal('testplural');
        });
    });

    describe('.registerLoopbackModelForCollection', function() {
        it('should register loopback model for an existing collection JSON schema', function(done) {
            var jsonSchema = JsonSchema.create({ modelName: 'person', collectionName: 'people' });

            var next = function() {
                var Person = loopback.getModel('person');
                expect(Person).to.not.be.null;
                expect(Person.definition.name).to.equal("person");
                expect(Person.definition.settings.plural).to.equal("people");
                done();
            };
            JsonSchema.registerLoopbackModelForCollection("people", app, next);

            JsonSchema.remove({ modelName: 'person' });
        });

        it('should log when collection JSON schema was not found', function(done) {
            var log = sinon.stub(console, "warn");
            var next = function() {
                expect(log).to.have.been.calledWith("JSON Schema for collectionName:", "people", "Not found.");
                done();
            };

            JsonSchema.registerLoopbackModelForCollection("people", app, next);
        });

        xit('should log error when some problem happened with the JSON schema query', function() {
            // simulate error and assert log has been called
        });
    });
});
<|endoftext|>


<commit_before>require('tree-multiselect');

var Util = require('utility');

QUnit.module("Title Autochecking", {
  beforeEach: function(assert) {
    var select = document.createElement("select");
    select.setAttribute("multiple", "multiple");
    $("div#qunit-fixture").append(select);
    assert.equal($("select").length, 1);
  }
});

QUnit.test("section checkboxes should be checked when all children are selected initially", function(assert) {
  $("select").append("<option value='one' data-section='foo' selected='selected'>One</option>");
  $("select").append("<option value='two' data-section='foo' selected='selected'>Two</option>");
  $("select").treeMultiselect();

  assert.equal($("input[type=checkbox]").length, 3);
  assert.equal($("div.item > input[type=checkbox]").length, 2);
  assert.equal($("input[type=checkbox]:checked").length, 3);
});

QUnit.test("section checkboxes should be checked when all children are selected", function(assert) {
  $("select").append("<option value='one' data-section='foo' selected='selected'>One</option>");
  $("select").append("<option value='two' data-section='foo'>Two</option>");
  $("select").treeMultiselect();

  assert.equal($("input[type=checkbox]:checked").length, 1);

  var lastItem = $("div.selections div.item").last();
  lastItem.find("> input[type=checkbox]").prop('checked', true).trigger('change');

  assert.equal($("input[type=checkbox]:checked").length, 3);
});

QUnit.test("top level parent should not be checked if only one child section is completely checked", function(assert) {
  $("select").append("<option value='one' data-section='foo/bar' selected='selected'>One</option>");
  $("select").append("<option value='two' data-section='foo/baz'>Two</option>");
  $("select").treeMultiselect();

  var topLevel = $("div.section").first();
  assert.ok(!(topLevel.find("> div.title > input[type=checkbox]").is(":checked")));
});

QUnit.test("top level parent checking with only one child section completely checked, now with triggers", function(assert) {
  $("select").append("<option value='one' data-section='foo/bar' selected='selected'>One</option>");
  $("select").append("<option value='two' data-section='foo/bar'>Two</option>");
  $("select").append("<option value='three' data-section='foo/baz'>Three</option>");
  $("select").treeMultiselect();

  var topLevel = $("div.section").first();
  assert.ok(!(topLevel.find("> div.title > input[type=checkbox]").is(":checked")));

  var barSection = $("div.section").filter(function() {
    return Util.textOf($(this).find("> div.title")) == 'bar';
  });
  assert.equal(barSection.length, 1);
  assert.ok(!(barSection.find("> div.title > input[type=checkbox]").is(":checked")));

  barSection.find("div.item > input[type=checkbox]").prop('checked', true).trigger('change');

  assert.ok(barSection.find("> div.title > input[type=checkbox]").is(":checked"));
  assert.ok(!(topLevel.find("> div.title > input[type=checkbox]").is(":checked")));
});

QUnit.test("titles should unselect when a child is unselected", function(assert) {
  $("select").append("<option value='one' data-section='foo' selected='selected'>One</option>");
  $("select").treeMultiselect();

  assert.ok($("div.title > input[type=checkbox]").is(":checked"));

  var item = $("div.item > input[type=checkbox]").first();
  item.prop("checked", false);
  item.trigger('change');

  assert.ok(!($("div.title > input[type=checkbox]").is(":checked")));
});

QUnit.test("nested titles should all be checked if a title is batch selected", function(assert) {
  console.log("BEGIN TEST");
  $("select").append("<option value='one' data-section='top/middle/inner'>One</option>");
  $("select").treeMultiselect();

  assert.equal($("input[type=checkbox]").length, 4);
  assert.equal($("input[type=checkbox]:checked").length, 0);

  var middleSection = $("div.section").filter(function() {
    return Util.textOf($(this).find("> div.title")) == 'middle';
  });

  middleSection.find("> div.title > input[type=checkbox]").click();

  assert.equal($("input[type=checkbox]").length, 4);
  assert.equal($("input[type=checkbox]:checked").length, 3);
  console.log("END TEST");
});

QUnit.test("title checkbox is indeterminate when some but not all options are selected", function(assert) {
  $("select").append("<option value='one' data-section='top'>One</option>");
  $("select").append("<option value='two' data-section='top' selected='selected'>Two</option>");
  $("select").treeMultiselect();

  var titleCheckbox = $("div.selections").find("div.title > input[type=checkbox]");
  assert.equal(titleCheckbox.length, 1);
  assert.ok(titleCheckbox.prop('indeterminate'));
});

QUnit.test("title checkbox turns indeterminate when some options are selected", function(assert) {
  $("select").append("<option value='one' data-section='top'>One</option>");
  $("select").append("<option value='two' data-section='top'>Two</option>");
  $("select").treeMultiselect();

  var lastCheckbox = $("div.selections").find("div.item > input[type=checkbox]").last();
  lastCheckbox.prop('checked', true).trigger('change');

  var titleCheckbox = $("div.selections").find("div.title > input[type=checkbox]");
  assert.ok(titleCheckbox.prop('indeterminate'));
});

QUnit.test("title checkbox is not indeterminate when all options are selected", function(assert) {
  $("select").append("<option value='one' data-section='top'>One</option>");
  $("select").append("<option value='two' data-section='top'>Two</option>");
  $("select").treeMultiselect();

  var checkboxes = $("div.selections").find("input[type=checkbox]");
  checkboxes.prop('checked', true).trigger('change');

  var titleCheckbox = $("div.selections").find("div.title > input[type=checkbox]");
  assert.ok(!(titleCheckbox.prop('indeterminate')));
});

QUnit.test("title checkbox is not indeterminate when no options are selected", function(assert) {
  $("select").append("<option value='one' data-section='top'>One</option>");
  $("select").append("<option value='two' data-section='top' selected='selected'>Two</option>");
  $("select").treeMultiselect();

  var checkedCheckboxes = $("div.selections").find("input[type=checkbox]:checked");
  checkedCheckboxes.prop('checked', false).trigger('change');

  var titleCheckbox = $("div.selections").find("div.title > input[type=checkbox]");
  assert.ok(!(titleCheckbox.prop('indeterminate')));
});
<commit_msg>Tests work<commit_after>require('tree-multiselect');

var Util = require('utility');

QUnit.module("Title Autochecking", {
  beforeEach: function(assert) {
    var select = document.createElement("select");
    select.setAttribute("multiple", "multiple");
    $("div#qunit-fixture").append(select);
    assert.equal($("select").length, 1);
  }
});

QUnit.test("section checkboxes should be checked when all children are selected initially", function(assert) {
  $("select").append("<option value='one' data-section='foo' selected='selected'>One</option>");
  $("select").append("<option value='two' data-section='foo' selected='selected'>Two</option>");
  $("select").treeMultiselect();

  assert.equal($("input[type=checkbox]").length, 3);
  assert.equal($("div.item > input[type=checkbox]").length, 2);
  assert.equal($("input[type=checkbox]:checked").length, 3);
});

QUnit.test("section checkboxes should be checked when all children are selected", function(assert) {
  $("select").append("<option value='one' data-section='foo' selected='selected'>One</option>");
  $("select").append("<option value='two' data-section='foo'>Two</option>");
  $("select").treeMultiselect();

  assert.equal($("input[type=checkbox]:checked").length, 1);

  var lastItem = $("div.selections div.item").last();
  lastItem.find("> input[type=checkbox]").prop('checked', true).trigger('change');

  assert.equal($("input[type=checkbox]:checked").length, 3);
});

QUnit.test("top level parent should not be checked if only one child section is completely checked", function(assert) {
  $("select").append("<option value='one' data-section='foo/bar' selected='selected'>One</option>");
  $("select").append("<option value='two' data-section='foo/baz'>Two</option>");
  $("select").treeMultiselect();

  var topLevel = $("div.section").first();
  assert.ok(!(topLevel.find("> div.title > input[type=checkbox]").is(":checked")));
});

QUnit.test("top level parent checking with only one child section completely checked, now with triggers", function(assert) {
  $("select").append("<option value='one' data-section='foo/bar' selected='selected'>One</option>");
  $("select").append("<option value='two' data-section='foo/bar'>Two</option>");
  $("select").append("<option value='three' data-section='foo/baz'>Three</option>");
  $("select").treeMultiselect();

  var topLevel = $("div.section").first();
  assert.ok(!(topLevel.find("> div.title > input[type=checkbox]").is(":checked")));

  var barSection = $("div.section").filter(function() {
    return Util.textOf($(this).find("> div.title")) == 'bar';
  });
  assert.equal(barSection.length, 1);
  assert.ok(!(barSection.find("> div.title > input[type=checkbox]").is(":checked")));

  barSection.find("div.item > input[type=checkbox]").prop('checked', true).trigger('change');

  assert.ok(barSection.find("> div.title > input[type=checkbox]").is(":checked"));
  assert.ok(!(topLevel.find("> div.title > input[type=checkbox]").is(":checked")));
});

QUnit.test("titles should unselect when a child is unselected", function(assert) {
  $("select").append("<option value='one' data-section='foo' selected='selected'>One</option>");
  $("select").treeMultiselect();

  assert.ok($("div.title > input[type=checkbox]").is(":checked"));

  var item = $("div.item > input[type=checkbox]").first();
  item.prop("checked", false);
  item.trigger('change');

  assert.ok(!($("div.title > input[type=checkbox]").is(":checked")));
});

QUnit.test("nested titles should all be checked if a title is batch selected", function(assert) {
  console.log("BEGIN TEST");
  $("select").append("<option value='one' data-section='top/middle/inner'>One</option>");
  $("select").append("<option value='two' data-section='top'>Two</option>");
  $("select").treeMultiselect();

  assert.equal($("div.title > input[type=checkbox]").length, 3);
  assert.equal($("div.item > input[type=checkbox]").length, 2);
  assert.equal($("input[type=checkbox]").length, 5);
  assert.equal($("input[type=checkbox]:checked").length, 0);

  var middleSection = $("div.section").filter(function() {
    return Util.textOf($(this).find("> div.title")) == 'middle';
  });

  middleSection.find("> div.title > input[type=checkbox]").click();

  assert.equal($("div.title > input[type=checkbox]:checked").length, 2);
  assert.equal($("div.item > input[type=checkbox]:checked").length, 1);
  assert.equal($("input[type=checkbox]:checked").length, 3);
  console.log("END TEST");
});

QUnit.test("title checkbox is indeterminate when some but not all options are selected", function(assert) {
  $("select").append("<option value='one' data-section='top'>One</option>");
  $("select").append("<option value='two' data-section='top' selected='selected'>Two</option>");
  $("select").treeMultiselect();

  var titleCheckbox = $("div.selections").find("div.title > input[type=checkbox]");
  assert.equal(titleCheckbox.length, 1);
  assert.ok(titleCheckbox.prop('indeterminate'));
});

QUnit.test("title checkbox turns indeterminate when some options are selected", function(assert) {
  $("select").append("<option value='one' data-section='top'>One</option>");
  $("select").append("<option value='two' data-section='top'>Two</option>");
  $("select").treeMultiselect();

  var lastCheckbox = $("div.selections").find("div.item > input[type=checkbox]").last();
  lastCheckbox.prop('checked', true).trigger('change');

  var titleCheckbox = $("div.selections").find("div.title > input[type=checkbox]");
  assert.ok(titleCheckbox.prop('indeterminate'));
});

QUnit.test("title checkbox is not indeterminate when all options are selected", function(assert) {
  $("select").append("<option value='one' data-section='top'>One</option>");
  $("select").append("<option value='two' data-section='top'>Two</option>");
  $("select").treeMultiselect();

  var checkboxes = $("div.selections").find("input[type=checkbox]");
  checkboxes.prop('checked', true).trigger('change');

  var titleCheckbox = $("div.selections").find("div.title > input[type=checkbox]");
  assert.ok(!(titleCheckbox.prop('indeterminate')));
});

QUnit.test("title checkbox is not indeterminate when no options are selected", function(assert) {
  $("select").append("<option value='one' data-section='top'>One</option>");
  $("select").append("<option value='two' data-section='top' selected='selected'>Two</option>");
  $("select").treeMultiselect();

  var checkedCheckboxes = $("div.selections").find("input[type=checkbox]:checked");
  checkedCheckboxes.prop('checked', false).trigger('change');

  var titleCheckbox = $("div.selections").find("div.title > input[type=checkbox]");
  assert.ok(!(titleCheckbox.prop('indeterminate')));
});
<|endoftext|>


<commit_before>/**
 * @fileOverview Testing Mongoose normalize methods.
 */
var __ = require('lodash');
var Promise = require('bluebird');
// var sinon  = require('sinon');
var chai = require('chai');
var expect = chai.expect;
// var sinon = require('sinon');
var assert = chai.assert;

var fix = require('../fixture/data.fix');
var mongStub = require('../lib/mongoose-stub');

suite('Mongoose Normalization Methods', function() {
  setup(mongStub.connect);
  setup(mongStub.nukedb);

  mongStub.setupRecords();

  suite('Normal Operation', function() {
    test('Should normalize results', function() {
      this.entity.read.after(this.entity.normalize);

      return this.entity.read()
        .bind(this)
        .then(function(res) {
          expect(res[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle an already normalized set of items', function() {
      this.entity.read.after(this.entity.normalize);

      return this.entity.read()
        .bind(this)
        .then(function(res) {
          var sanres = this.entity.mongooseNormalize.normalize(res);

          expect(sanres[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle empty results', function() {
      this.entity.read.after(this.entity.normalize);

      return this.entity.read({name: 'none'})
        .bind(this)
        .then(function(res) {
          assert.isArray(res, 'Result should be an array');
          assert.lengthOf(res, 0, 'Should have zero results');
        });
    });

    test('Should normalize single item reads', function() {
      this.entity.readOne.after(this.entity.normalize);

      return this.entity.readOne({name: fix.one.name})
        .bind(this)
        .then(function(res) {
          expect(res).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle an already normalized single object', function() {
      this.entity.readOne.after(this.entity.normalize);

      return this.entity.readOne({name: fix.one.name})
        .bind(this)
        .then(function(res) {
          var sanres = this.entity.mongooseNormalize.normalize(res);

          expect(sanres).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle no results for single item reads', function() {
      this.entity.readOne.after(this.entity.normalize);

      return this.entity.readOne({name: 'none'})
        .bind(this)
        .then(function(res) {
          assert.isNull(res, 'Result should be a null');
        });
    });

    test('Should normalize create op', function() {
      this.entity.create.after(this.entity.normalize);

      return this.entity.create(fix.one)
        .bind(this)
        .then(function(res) {
          expect(res).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize update op', function() {
      this.entity.update.after(this.entity.normalize);

      return this.entity.update({name: fix.one.name}, {name: fix.one.name})
        .bind(this)
        .then(function(res) {
          expect(res).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize read limit', function() {
      this.entity.readLimit.after(this.entity.normalize);

      return this.entity.readLimit(null, 0, 10)
        .bind(this)
        .then(function(res) {
          expect(res[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
  });
  suite('Middleware', function() {
    test('Should return expected result', function() {
      this.entity.readLimit.after(this.entity.normalize);

      this.entity.readLimit.after(function(query, offset, limit, items) {
        return items.map(function(item) {
          item.lol = 1;
          return item;
        });
      });

      return this.entity.readLimit(null, 0, 10)
        .bind(this)
        .then(function(res) {
          expect(res[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
            'lol',
          ]);
        });
    });
  });

  suite('Relations', function() {
    test('Should normalize single item reads', function() {
      this.entityRel.readOne.after(this.entityRel.normalize);

      return this.entityRel.readOne({darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          expect(res.parent).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle an already normalized single object', function() {
      this.entityRel.readOne.after(this.entityRel.normalize);

      return this.entityRel.readOne({darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          var sanres = this.entityRel.mongooseNormalize.normalize(res);

          expect(sanres.parent).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle no results for single item reads', function() {
      this.entityRel.readOne.after(this.entityRel.normalize);

      return this.entityRel.readOne({darname: 'none'})
        .bind(this)
        .then(function(res) {
          assert.isNull(res, 'Result should be a null');
        });
    });

    test('Should normalize create op', function() {
      this.entityRel.create.after(this.entityRel.normalize);
      var fixThree = __.clone(fix.relThree);
      fixThree.parent = this.recordTwo._id;

      return this.entityRel.create(fixThree)
        .bind(this)
        .then(function(res) {
          expect(res.parent).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize update op', function() {
      this.entityRel.update.after(this.entityRel.normalize);

      return this.entityRel.update({darname: fix.relOne.darname},
        {darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          expect(res.parent).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize read limit', function() {
      this.entityRel.readLimit.after(this.entityRel.normalize);

      return this.entityRel.readLimit(null, 0, 10)
        .bind(this)
        .then(function(res) {
          expect(res[0].parent).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
  });

  suite('Relations Multy', function() {
    test('Should normalize single item reads', function() {
      this.entityRelMult.readOne.after(this.entityRelMult.normalize);

      return this.entityRelMult.readOne({darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          expect(res.parents).to.be.an('array');
          expect(res.parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle an already normalized single object', function() {
      this.entityRelMult.readOne.after(this.entityRelMult.normalize);

      return this.entityRelMult.readOne({darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          var sanres = this.entityRelMult.mongooseNormalize.normalize(res);
          expect(sanres.parents).to.be.an('array');
          expect(sanres.parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle no results for single item reads', function() {
      this.entityRelMult.readOne.after(this.entityRelMult.normalize);

      return this.entityRelMult.readOne({darname: 'none'})
        .bind(this)
        .then(function(res) {
          assert.isNull(res, 'Result should be a null');
        });
    });

    test('Should normalize create op', function() {
      this.entityRelMult.create.after(this.entityRelMult.normalize);
      var fixThree = __.clone(fix.relThree);
      fixThree.parents = [this.recordTwo._id];

      return this.entityRelMult.create(fixThree)
        .bind(this)
        .then(function(res) {
          expect(res.parents).to.be.an('array');
          expect(res.parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize update op', function() {
      this.entityRelMult.update.after(this.entityRelMult.normalize);

      return this.entityRelMult.update({darname: fix.relOne.darname},
        {darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          expect(res.parents).to.be.an('array');
          expect(res.parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize read limit', function() {
      this.entityRelMult.readLimit.after(this.entityRelMult.normalize);

      return this.entityRelMult.readLimit(null, 0, 10)
        .bind(this)
        .then(function(res) {
          expect(res[0].parents).to.be.an('array');
          expect(res[0].parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize read', function() {
      this.entityRelMult.read.after(this.entityRelMult.normalize);

      return this.entityRelMult.read()
        .bind(this)
        .then(function(res) {
          expect(res[0].parents).to.be.an('array');
          expect(res[0].parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

  });

});
<commit_msg>finalize test cases<commit_after>/**
 * @fileOverview Testing Mongoose normalize methods.
 */
var __ = require('lodash');
var Promise = require('bluebird');
// var sinon  = require('sinon');
var chai = require('chai');
var expect = chai.expect;
// var sinon = require('sinon');
var assert = chai.assert;

var fix = require('../fixture/data.fix');
var mongStub = require('../lib/mongoose-stub');

suite('Mongoose Normalization Methods', function() {
  setup(mongStub.connect);
  setup(mongStub.nukedb);

  mongStub.setupRecords();

  suite('Normal Operation', function() {
    test('Should normalize results', function() {
      this.entity.read.after(this.entity.normalize);

      return this.entity.read()
        .bind(this)
        .then(function(res) {
          expect(res[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle an already normalized set of items', function() {
      this.entity.read.after(this.entity.normalize);

      return this.entity.read()
        .bind(this)
        .then(function(res) {
          var sanres = this.entity.mongooseNormalize.normalize(res);

          expect(sanres[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle empty results', function() {
      this.entity.read.after(this.entity.normalize);

      return this.entity.read({name: 'none'})
        .bind(this)
        .then(function(res) {
          assert.isArray(res, 'Result should be an array');
          assert.lengthOf(res, 0, 'Should have zero results');
        });
    });

    test('Should normalize single item reads', function() {
      this.entity.readOne.after(this.entity.normalize);

      return this.entity.readOne({name: fix.one.name})
        .bind(this)
        .then(function(res) {
          expect(res).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle an already normalized single object', function() {
      this.entity.readOne.after(this.entity.normalize);

      return this.entity.readOne({name: fix.one.name})
        .bind(this)
        .then(function(res) {
          var sanres = this.entity.mongooseNormalize.normalize(res);

          expect(sanres).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle no results for single item reads', function() {
      this.entity.readOne.after(this.entity.normalize);

      return this.entity.readOne({name: 'none'})
        .bind(this)
        .then(function(res) {
          assert.isNull(res, 'Result should be a null');
        });
    });

    test('Should normalize create op', function() {
      this.entity.create.after(this.entity.normalize);

      return this.entity.create(fix.one)
        .bind(this)
        .then(function(res) {
          expect(res).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize update op', function() {
      this.entity.update.after(this.entity.normalize);

      return this.entity.update({name: fix.one.name}, {name: fix.one.name})
        .bind(this)
        .then(function(res) {
          expect(res).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize read limit', function() {
      this.entity.readLimit.after(this.entity.normalize);

      return this.entity.readLimit(null, 0, 10)
        .bind(this)
        .then(function(res) {
          expect(res[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
  });
  suite('Middleware', function() {
    test('Should return expected result', function() {
      this.entity.readLimit.after(this.entity.normalize);

      this.entity.readLimit.after(function(query, offset, limit, items) {
        return items.map(function(item) {
          item.lol = 1;
          return item;
        });
      });

      return this.entity.readLimit(null, 0, 10)
        .bind(this)
        .then(function(res) {
          expect(res[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
            'lol',
          ]);
        });
    });
  });

  suite('Relations', function() {
    test('Should normalize single item reads', function() {
      this.entityRel.readOne.after(this.entityRel.normalize);

      return this.entityRel.readOne({darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          expect(res.parent).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle an already normalized single object', function() {
      this.entityRel.readOne.after(this.entityRel.normalize);

      return this.entityRel.readOne({darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          var sanres = this.entityRel.mongooseNormalize.normalize(res);

          expect(sanres.parent).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle no results for single item reads', function() {
      this.entityRel.readOne.after(this.entityRel.normalize);

      return this.entityRel.readOne({darname: 'none'})
        .bind(this)
        .then(function(res) {
          assert.isNull(res, 'Result should be a null');
        });
    });

    test('Should normalize create op', function() {
      this.entityRel.create.after(this.entityRel.normalize);
      var fixThree = __.clone(fix.relThree);
      fixThree.parent = this.recordTwo._id;

      return this.entityRel.create(fixThree)
        .bind(this)
        .then(function(res) {
          expect(res.parent).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize update op', function() {
      this.entityRel.update.after(this.entityRel.normalize);

      return this.entityRel.update({darname: fix.relOne.darname},
        {darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          expect(res.parent).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize read limit', function() {
      this.entityRel.readLimit.after(this.entityRel.normalize);

      return this.entityRel.readLimit(null, 0, 10)
        .bind(this)
        .then(function(res) {
          expect(res[0].parent).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize read', function() {
      this.entityRel.read.after(this.entityRel.normalize);

      return this.entityRel.read()
        .bind(this)
        .then(function(res) {
          expect(res[0].parent).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
  });

  suite('Relations Multy', function() {
    test('Should normalize single item reads', function() {
      this.entityRelMult.readOne.after(this.entityRelMult.normalize);

      return this.entityRelMult.readOne({darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          expect(res.parents).to.be.an('array');
          expect(res.parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle an already normalized single object', function() {
      this.entityRelMult.readOne.after(this.entityRelMult.normalize);

      return this.entityRelMult.readOne({darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          var sanres = this.entityRelMult.mongooseNormalize.normalize(res);
          expect(sanres.parents).to.be.an('array');
          expect(sanres.parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });

    test('Should handle no results for single item reads', function() {
      this.entityRelMult.readOne.after(this.entityRelMult.normalize);

      return this.entityRelMult.readOne({darname: 'none'})
        .bind(this)
        .then(function(res) {
          assert.isNull(res, 'Result should be a null');
        });
    });

    test('Should normalize create op', function() {
      this.entityRelMult.create.after(this.entityRelMult.normalize);
      var fixThree = __.clone(fix.relThree);
      fixThree.parents = [this.recordTwo._id];

      return this.entityRelMult.create(fixThree)
        .bind(this)
        .then(function(res) {
          expect(res.parents).to.be.an('array');
          expect(res.parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize update op', function() {
      this.entityRelMult.update.after(this.entityRelMult.normalize);

      return this.entityRelMult.update({darname: fix.relOne.darname},
        {darname: fix.relOne.darname})
        .bind(this)
        .then(function(res) {
          expect(res.parents).to.be.an('array');
          expect(res.parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize read limit', function() {
      this.entityRelMult.readLimit.after(this.entityRelMult.normalize);

      return this.entityRelMult.readLimit(null, 0, 10)
        .bind(this)
        .then(function(res) {
          expect(res[0].parents).to.be.an('array');
          expect(res[0].parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
    test('Should normalize read', function() {
      this.entityRelMult.read.after(this.entityRelMult.normalize);

      return this.entityRelMult.read()
        .bind(this)
        .then(function(res) {
          expect(res[0].parents).to.be.an('array');
          expect(res[0].parents[0]).to.have.keys([
            'id',
            'name',
            'sortby',
            '_isActive',
          ]);
        });
    });
  });
});
<|endoftext|>


<commit_before>const Telegraf = require('../')
const { Extra, memorySession, reply } = require('../')

const bot = new Telegraf(process.env.BOT_TOKEN)

bot.use(memorySession())

// Register logger middleware
bot.use((ctx, next) => {
  const start = new Date()
  return next().then(() => {
    const ms = new Date() - start
    console.log('response time %sms', ms)
  })
})

const sayYoMiddleware = ({ reply }, next) => reply('yo').then(next)

// Random location on some text messages
bot.on('text', ({ replyWithLocation }, next) => {
  if (Math.random() > 0.2) {
    return next()
  }
  return Promise.all([
    replyWithLocation((Math.random() * 180) - 90, (Math.random() * 180) - 90),
    next()
  ])
})

// Text messages handling
bot.hears('Hey', sayYoMiddleware, (ctx) => {
  ctx.session.heyCounter = ctx.session.heyCounter || 0
  ctx.session.heyCounter++
  return ctx.replyWithMarkdown(`_Hey counter:_ ${ctx.session.heyCounter}`)
})

// Command handling
bot.command('answer', sayYoMiddleware, (ctx) => {
  console.log(ctx.message)
  return ctx.reply('*42*', Extra.markdown())
})

const catPhoto = 'http://lorempixel.com/400/200/cats/'
bot.command('cat', ({ replyWithPhoto }) => replyWithPhoto(catPhoto))

// Streaming photo, in case Telegram does't accept url directly
bot.command('cat2', ({ replyWithPhoto }) => replyWithPhoto({ url: catPhoto }))

// Look ma, reply middleware factory
bot.command('foo', reply('http://coub.com/view/9cjmt'))

// Wow! RegEx
bot.hears(/reverse (.+)/, ({ match, reply }) => {
  return reply(match[1].split('').reverse().join(''))
})

// Start polling
bot.startPolling()
<commit_msg>fix #177<commit_after>const Telegraf = require('../')
const { Extra, memorySession, reply } = require('../')

const bot = new Telegraf(process.env.BOT_TOKEN)

bot.use(memorySession())

// Register logger middleware
bot.use((ctx, next) => {
  const start = new Date()
  return next().then(() => {
    const ms = new Date() - start
    console.log('response time %sms', ms)
  })
})

const sayYoMiddleware = ({ reply }, next) => reply('yo').then(() => next())

// Random location on some text messages
bot.on('text', ({ replyWithLocation }, next) => {
  if (Math.random() > 0.2) {
    return next()
  }
  return Promise.all([
    replyWithLocation((Math.random() * 180) - 90, (Math.random() * 180) - 90),
    next()
  ])
})

// Text messages handling
bot.hears('Hey', sayYoMiddleware, (ctx) => {
  ctx.session.heyCounter = ctx.session.heyCounter || 0
  ctx.session.heyCounter++
  return ctx.replyWithMarkdown(`_Hey counter:_ ${ctx.session.heyCounter}`)
})

// Command handling
bot.command('answer', sayYoMiddleware, (ctx) => {
  console.log(ctx.message)
  return ctx.reply('*42*', Extra.markdown())
})

const catPhoto = 'http://lorempixel.com/400/200/cats/'
bot.command('cat', ({ replyWithPhoto }) => replyWithPhoto(catPhoto))

// Streaming photo, in case Telegram does't accept url directly
bot.command('cat2', ({ replyWithPhoto }) => replyWithPhoto({ url: catPhoto }))

// Look ma, reply middleware factory
bot.command('foo', reply('http://coub.com/view/9cjmt'))

// Wow! RegEx
bot.hears(/reverse (.+)/, ({ match, reply }) => {
  return reply(match[1].split('').reverse().join(''))
})

// Start polling
bot.startPolling()
<|endoftext|>


<commit_before>'use strict';

const autocompletePrompt = require('cli-autocomplete');
const chalk = require('chalk');

const ecolect = require('../');
const en = require('../language/en');
const any = require('../values/any');
const date = require('../values/date');
const number = require('../values/number');
const enumeration = require('../values/enumeration');

const intents = ecolect.intents(en)
	.intent('todo:list')
		.add('all todos')
		.add('show me my todos')
		.done()
	.intent('todo:create')
		.value('text', any())
		.add('add {text}')
		.add('add {text} to my todo list')
		.add('add {text} to my todo')
		.done()
	.intent('todo:deadline')
		.value('date', date())
		.value('count', number())
		.add('todos for {date}')
		.add('show me todos for {date}')
		.add('top {count} for {date}')
		.done()
	.intent('tods:for')
		.value('tags', enumeration([ 'Cookie Co', 'Do Later' ]))
		.add('todos marked {tags}')
		.add('show me todos marked {tags}')
		.done()
	.build();

function formatValue(value) {
	if(value && value.value) {
		return value.value;
	}
	return value;
}

function run() {
	autocompletePrompt('', query => {
		return intents.match(query, {
			partial: true
		}).then(results =>
			(results.matches || []).map(item => {
				const title = item.expression.map(e => {
					switch(e.type) {
						case 'value':
							return chalk.green(formatValue(e.value) || e.id);
						default:
							return e.value;
					}
				}).join(' ');
				return {
					title: chalk.gray(item.score.toFixed(2)) + '  ' + title
				}
			})
		).catch(err => console.log(err));
	}).on('submit', query => {
		if(! query) {
			run();
			return;
		}

		intents.match(query).then(r => {
			if(r.best) {
				console.log('Matched ' + r.best.intent);
			} else {
				console.log('Did not match');
			}

			run();
		});
	});
}

console.log('Type to test matching');
run();
<commit_msg>chore: Update Example CLI with better date formatting<commit_after>'use strict';

const autocompletePrompt = require('cli-autocomplete');
const chalk = require('chalk');

const ecolect = require('../');
const en = require('../language/en');
const any = require('../values/any');
const date = require('../values/date');
const number = require('../values/number');
const enumeration = require('../values/enumeration');

const intents = ecolect.intents(en)
	.intent('todo:list')
		.add('all todos')
		.add('show me my todos')
		.done()
	.intent('todo:create')
		.value('text', any())
		.add('add {text}')
		.add('add {text} to my todo list')
		.add('add {text} to my todo')
		.done()
	.intent('todo:deadline')
		.value('date', date())
		.value('count', number())
		.add('todos for {date}')
		.add('show me todos for {date}')
		.add('top {count} for {date}')
		.done()
	.intent('tods:for')
		.value('tags', enumeration([ 'Cookie Co', 'Do Later' ]))
		.add('todos marked {tags}')
		.add('show me todos marked {tags}')
		.done()
	.build();

function formatValue(value) {
	if(value) {
		if(value.value) {
			return value.value;
		} else if(value.toDate) {
			return value.toDate();
		}
	}
	return value;
}

function run() {
	autocompletePrompt('', query => {
		return intents.match(query, {
			partial: true
		}).then(results =>
			(results.matches || []).map(item => {
				const title = item.expression.map(e => {
					switch(e.type) {
						case 'value':
							return chalk.green(formatValue(e.value) || e.id);
						default:
							return e.value;
					}
				}).join(' ');
				return {
					title: chalk.gray(item.score.toFixed(2)) + '  ' + title
				}
			})
		).catch(err => console.log(err));
	}).on('submit', query => {
		if(! query) {
			run();
			return;
		}

		intents.match(query).then(r => {
			if(r.best) {
				console.log('Matched ' + r.best.intent);
			} else {
				console.log('Did not match');
			}

			run();
		});
	});
}

console.log('Type to test matching');
run();
<|endoftext|>


<commit_before>/* test/browser/system_controllers_test.js -- test System angular controllers
 * Copyright 2014 Sergei Ianovich
 *
 * Licensed under AGPL-3.0 or later, see LICENSE
 * Process Control Service Web Interface
 */
'use strict';

describe("System Controllers", function() {
  beforeEach(function() {
    angular.mock.module('pcs.services');
    angular.mock.module('pcs.controllers');
  });

  var httpBackend;

  beforeEach(inject(function($httpBackend) {
    httpBackend = $httpBackend;
  }));

  afterEach(function(){
    httpBackend.verifyNoOutstandingExpectation();
  });

  var location, controller;

  beforeEach(inject(function($location, $controller) {
    location = $location;
    controller = $controller;
  }));

  describe("NewSystemCtrl", function() {
    var scope, routeParams;

    beforeEach(function() {
      routeParams = { siteId: 2 };
      scope = {
        $on: sinon.spy(),
        page: sinon.spy(),
        setNewURL: sinon.spy(),
      };
      httpBackend.expectGET('/sites/2').respond({_id: 2, name: "site"});
      controller('NewSystemCtrl', { $scope: scope, $routeParams: routeParams });
    });

    it("should clear pager", function() {
      expect(scope.page).to.have.been.calledWith(1, 1, 0);
    });

    it("should clear setNewURL", function() {
      expect(scope.setNewURL).to.have.been.calledWith(null);
    });

    it("should create system in scope", function() {
      expect(scope.system).to.exist();
      expect(scope.system.site).to.equal(2);
    });

    it("should init binding buffer", function() {
      expect(scope.n).to.eql({});
    });

    describe("#updateDevice", function() {
      describe("when device not found", function() {
        it ("should clear device", function() {
          scope.n.deviceName = "a";
          scope.device = { _id: 2 };
          scope.system.device = 2;
          httpBackend.expectGET('/devices?name=a').respond([{count: 0}]);
          scope.updateDevice();
          httpBackend.flush();
          expect(scope.system.device).to.equal(null);
          expect(scope.device).to.eql({});
        });
      });

      describe("when device found", function() {
        it("should assign device", function() {
          scope.n.deviceName = "b";
          httpBackend.expectGET('/devices?name=b').respond([{_id: 2, name: "device"}, {count: 1}]);
          scope.updateDevice();
          httpBackend.flush();
          expect(scope.system.device).to.equal(2);
          expect(JSON.stringify(scope.device)).to.eql(JSON.stringify({_id: 2, name: "device"}));
        });
      });
    });

    describe("#save", function() {
      beforeEach(function() {
        scope.systemForm = {
          $setPristine: sinon.spy(),
        };

        httpBackend.expectPOST('/sites/2/systems', {
          site: 2, name: "hello", device: 3
        }).respond({
          _id: 33, name: "hello", site: 2, device: 3, outputs: [], setpoints: {}
        });
        scope.system.name = "hello";
        scope.system.device = 3;
      });

      it("should save system", function() {
        scope.save();
      });

      it("should set the form pristine", function() {
        scope.save();
        httpBackend.flush();
        expect(scope.systemForm.$setPristine).to.have.been.called;
      });

      it("should change location path", function() {
        scope.save();
        httpBackend.flush();
        expect(location.path()).to.equal('/sites/2/systems/33');
      });
    });
  });

  describe("SystemCtrl", function() {
    var scope, routeParams;

    beforeEach(function() {
      scope = {
        $on: sinon.spy(),
        page: sinon.spy(),
        setNewURL: sinon.spy(),
      };
      routeParams = { siteId: 2, systemId: 1 };
      httpBackend.expectGET('/sites/2/systems/1').respond({
        _id: 1,
        name: "hello",
        site: 2,
        device: 3,
        outputs: ["a1"],
        setpoints: {a1: 5}
      });
      httpBackend.expectGET('/sites/2').respond({_id: 2, name: "site"});
      httpBackend.expectGET('/devices/3').respond({_id: 3, name: "device"});
      controller('SystemCtrl', { $scope: scope, $routeParams: routeParams });
      httpBackend.flush();
    });

    it("should clear pager", function() {
      expect(scope.page).to.have.been.calledWith(1, 1, 0);
    });

    it("should clear setNewURL", function() {
      expect(scope.setNewURL).to.have.been.calledWith(null);
    });

    it("should load system", function() {
      expect(scope.system).to.exist();
      expect(scope.system._id).to.equal(1);
      expect(scope.system.site).to.equal(2);
      expect(scope.system.device).to.equal(3);
      expect(scope.system.name).to.equal("hello");
    });

    it("should load site", function() {
      expect(scope.site).to.exist();
      expect(scope.site._id).to.equal(2);
      expect(scope.site.name).to.equal("site");
    });

    it("should init binding buffer", function() {
      expect(scope.n.deviceName).to.exist();
    });

    describe("#updateDevice", function() {
      describe("when device not found", function() {
        it ("should clear device", function() {
          scope.n.deviceName = "a";
          scope.device = { _id: 2 };
          scope.system.device = 2;
          httpBackend.expectGET('/devices?name=a').respond([{count: 0}]);
          scope.updateDevice();
          httpBackend.flush();
          expect(scope.system.device).to.equal(null);
          expect(scope.device).to.eql({});
        });
      });

      describe("when device found", function() {
        it("should assign device", function() {
          scope.n.deviceName = "b";
          httpBackend.expectGET('/devices?name=b').respond([{_id: 2, name: "device"}, {count: 1}]);
          scope.updateDevice();
          httpBackend.flush();
          expect(scope.system.device).to.equal(2);
          expect(JSON.stringify(scope.device)).to.eql(JSON.stringify({_id: 2, name: "device"}));
        });
      });
    });

    describe("#addOutput", function() {
      it("should add to system outputs", function() {
        scope.system = { outputs: [] };
        scope.n.out = "some";
        scope.addOutput();
        expect(scope.system.outputs.length).to.equal(1);
        expect(scope.system.outputs[0]).to.equal("some");
        expect(scope.n.out).to.eql(null);
      });
    });

    describe("#dropOutput", function() {
      it("should remove from system outputs", function() {
        scope.system = { outputs: ["some", "output"] };
        scope.systemForm = { $setDirty: sinon.spy() };
        scope.dropOutput(1);
        expect(scope.system.outputs).to.eql(["some"]);
        expect(scope.systemForm.$setDirty).to.have.been.called;
      });
    });

    describe("#addSetpoint", function() {
      it("add to system setpoints", function() {
        scope.system = { setpoints: { "some": "setpoint" } };
        scope.n.set = "other";
        scope.n.setValue = "setpoint";
        scope.addSetpoint();
        expect(scope.system.setpoints).to.eql({ "some": "setpoint", "other":"setpoint" });
        expect(scope.n.set).to.equal(null);
      });
    });

    describe("#dropSetpoint", function() {
      it("remove from system outputs", function() {
        scope.system = { setpoints: { "some": "setpoint", "other":"setpoint" } };
        scope.systemForm = { $setDirty: sinon.spy() };
        scope.dropSetpoint("some");
        expect(scope.system.setpoints).to.eql({ "other":"setpoint" });
        expect(scope.systemForm.$setDirty).to.have.been.called;
      });
    });

    describe("#save", function() {
      beforeEach(function() {
        scope.systemForm = {};
        scope.systemForm.$setPristine = sinon.spy();
        scope.$on = sinon.spy();
        httpBackend.expectPOST('/sites/2/systems/1', {
          _id: 1,
          name: "world",
          site: 2,
          device: 3,
          outputs: ["a1"],
          setpoints: {"a1":5}
        }).respond({_id: 1, name: "world"});
        scope.system.name = "world";
      });

      it("should save system", function() {
        scope.save();
      });

      it("should clear form", function() {
        scope.save();
        httpBackend.flush();
        expect(scope.systemForm.$setPristine).to.have.been.called;
      });
    });
  });
});
// vim:ts=2 sts=2 sw=2 et:
<commit_msg>check controller create updateDevice method<commit_after>/* test/browser/system_controllers_test.js -- test System angular controllers
 * Copyright 2014 Sergei Ianovich
 *
 * Licensed under AGPL-3.0 or later, see LICENSE
 * Process Control Service Web Interface
 */
'use strict';

describe("System Controllers", function() {
  beforeEach(function() {
    angular.mock.module('pcs.services');
    angular.mock.module('pcs.controllers');
  });

  var httpBackend;

  beforeEach(inject(function($httpBackend) {
    httpBackend = $httpBackend;
  }));

  afterEach(function(){
    httpBackend.verifyNoOutstandingExpectation();
  });

  var location, controller;

  beforeEach(inject(function($location, $controller) {
    location = $location;
    controller = $controller;
  }));

  describe("NewSystemCtrl", function() {
    var scope, routeParams, systemHelper;

    beforeEach(function() {
      routeParams = { siteId: 2 };
      scope = {
        $on: sinon.spy(),
        page: sinon.spy(),
        setNewURL: sinon.spy(),
      };
      systemHelper = {
        setDeviceUpdater: sinon.spy()
      };
      httpBackend.expectGET('/sites/2').respond({_id: 2, name: "site"});
      controller('NewSystemCtrl', { $scope: scope, $routeParams: routeParams, SystemHelper: systemHelper });
    });

    it("should clear pager", function() {
      expect(scope.page).to.have.been.calledWith(1, 1, 0);
    });

    it("should clear setNewURL", function() {
      expect(scope.setNewURL).to.have.been.calledWith(null);
    });

    it("should create system in scope", function() {
      expect(scope.system).to.exist();
      expect(scope.system.site).to.equal(2);
    });

    it("should init binding buffer", function() {
      expect(scope.n).to.eql({});
    });

    it("should create updateDevice method", function() {
      expect(systemHelper.setDeviceUpdater).to.have.been.calledWith(scope);
    });

    describe("#save", function() {
      beforeEach(function() {
        scope.systemForm = {
          $setPristine: sinon.spy(),
        };

        httpBackend.expectPOST('/sites/2/systems', {
          site: 2, name: "hello", device: 3
        }).respond({
          _id: 33, name: "hello", site: 2, device: 3, outputs: [], setpoints: {}
        });
        scope.system.name = "hello";
        scope.system.device = 3;
      });

      it("should save system", function() {
        scope.save();
      });

      it("should set the form pristine", function() {
        scope.save();
        httpBackend.flush();
        expect(scope.systemForm.$setPristine).to.have.been.called;
      });

      it("should change location path", function() {
        scope.save();
        httpBackend.flush();
        expect(location.path()).to.equal('/sites/2/systems/33');
      });
    });
  });

  describe("SystemCtrl", function() {
    var scope, routeParams;

    beforeEach(function() {
      scope = {
        $on: sinon.spy(),
        page: sinon.spy(),
        setNewURL: sinon.spy(),
      };
      routeParams = { siteId: 2, systemId: 1 };
      httpBackend.expectGET('/sites/2/systems/1').respond({
        _id: 1,
        name: "hello",
        site: 2,
        device: 3,
        outputs: ["a1"],
        setpoints: {a1: 5}
      });
      httpBackend.expectGET('/sites/2').respond({_id: 2, name: "site"});
      httpBackend.expectGET('/devices/3').respond({_id: 3, name: "device"});
      controller('SystemCtrl', { $scope: scope, $routeParams: routeParams });
      httpBackend.flush();
    });

    it("should clear pager", function() {
      expect(scope.page).to.have.been.calledWith(1, 1, 0);
    });

    it("should clear setNewURL", function() {
      expect(scope.setNewURL).to.have.been.calledWith(null);
    });

    it("should load system", function() {
      expect(scope.system).to.exist();
      expect(scope.system._id).to.equal(1);
      expect(scope.system.site).to.equal(2);
      expect(scope.system.device).to.equal(3);
      expect(scope.system.name).to.equal("hello");
    });

    it("should load site", function() {
      expect(scope.site).to.exist();
      expect(scope.site._id).to.equal(2);
      expect(scope.site.name).to.equal("site");
    });

    it("should init binding buffer", function() {
      expect(scope.n.deviceName).to.exist();
    });

    describe("#updateDevice", function() {
      describe("when device not found", function() {
        it ("should clear device", function() {
          scope.n.deviceName = "a";
          scope.device = { _id: 2 };
          scope.system.device = 2;
          httpBackend.expectGET('/devices?name=a').respond([{count: 0}]);
          scope.updateDevice();
          httpBackend.flush();
          expect(scope.system.device).to.equal(null);
          expect(scope.device).to.eql({});
        });
      });

      describe("when device found", function() {
        it("should assign device", function() {
          scope.n.deviceName = "b";
          httpBackend.expectGET('/devices?name=b').respond([{_id: 2, name: "device"}, {count: 1}]);
          scope.updateDevice();
          httpBackend.flush();
          expect(scope.system.device).to.equal(2);
          expect(JSON.stringify(scope.device)).to.eql(JSON.stringify({_id: 2, name: "device"}));
        });
      });
    });

    describe("#addOutput", function() {
      it("should add to system outputs", function() {
        scope.system = { outputs: [] };
        scope.n.out = "some";
        scope.addOutput();
        expect(scope.system.outputs.length).to.equal(1);
        expect(scope.system.outputs[0]).to.equal("some");
        expect(scope.n.out).to.eql(null);
      });
    });

    describe("#dropOutput", function() {
      it("should remove from system outputs", function() {
        scope.system = { outputs: ["some", "output"] };
        scope.systemForm = { $setDirty: sinon.spy() };
        scope.dropOutput(1);
        expect(scope.system.outputs).to.eql(["some"]);
        expect(scope.systemForm.$setDirty).to.have.been.called;
      });
    });

    describe("#addSetpoint", function() {
      it("add to system setpoints", function() {
        scope.system = { setpoints: { "some": "setpoint" } };
        scope.n.set = "other";
        scope.n.setValue = "setpoint";
        scope.addSetpoint();
        expect(scope.system.setpoints).to.eql({ "some": "setpoint", "other":"setpoint" });
        expect(scope.n.set).to.equal(null);
      });
    });

    describe("#dropSetpoint", function() {
      it("remove from system outputs", function() {
        scope.system = { setpoints: { "some": "setpoint", "other":"setpoint" } };
        scope.systemForm = { $setDirty: sinon.spy() };
        scope.dropSetpoint("some");
        expect(scope.system.setpoints).to.eql({ "other":"setpoint" });
        expect(scope.systemForm.$setDirty).to.have.been.called;
      });
    });

    describe("#save", function() {
      beforeEach(function() {
        scope.systemForm = {};
        scope.systemForm.$setPristine = sinon.spy();
        scope.$on = sinon.spy();
        httpBackend.expectPOST('/sites/2/systems/1', {
          _id: 1,
          name: "world",
          site: 2,
          device: 3,
          outputs: ["a1"],
          setpoints: {"a1":5}
        }).respond({_id: 1, name: "world"});
        scope.system.name = "world";
      });

      it("should save system", function() {
        scope.save();
      });

      it("should clear form", function() {
        scope.save();
        httpBackend.flush();
        expect(scope.systemForm.$setPristine).to.have.been.called;
      });
    });
  });
});
// vim:ts=2 sts=2 sw=2 et:
<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version.canvas = "2.4.0";
}
<commit_msg>ENYO-4044: Update version to 2.5.0-pre.1<commit_after>if (enyo && enyo.version) {
	enyo.version.canvas = "2.5.0-pre.1";
}
<|endoftext|>


<commit_before>module.exports = {
  presets: [
    ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', modules: false }],
    '@babel/preset-react',
    '@babel/preset-flow',
  ],
  plugins: [
    'babel-plugin-emotion',
    'babel-plugin-macros',
    '@babel/plugin-proposal-class-properties',
    '@babel/plugin-proposal-object-rest-spread',
    '@babel/plugin-proposal-export-default-from',
  ],
  env: {
    test: {
      presets: [['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage' }]],
      plugins: ['babel-plugin-require-context-hook', 'babel-plugin-dynamic-import-node'],
    },
  },
  overrides: [
    {
      test: './examples/vue-kitchen-sink',
      presets: ['babel-preset-vue'],
    },
    {
      test: [
        './lib/core/src/server',
        './lib/node-logger',
        './lib/codemod',
        './addons/storyshots',
        './addons/storysource/src/loader',
        './app/**/src/server/**',
        './dangerfile.js',
      ],
      presets: [
        [
          '@babel/preset-env',
          {
            shippedProposals: true,
            useBuiltIns: 'usage',
            targets: {
              node: '8.11',
            },
          },
        ],
      ],
    },
  ],
};
<commit_msg>Fix RN binaries<commit_after>module.exports = {
  presets: [
    ['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', modules: false }],
    '@babel/preset-react',
    '@babel/preset-flow',
  ],
  plugins: [
    'babel-plugin-emotion',
    'babel-plugin-macros',
    '@babel/plugin-proposal-class-properties',
    '@babel/plugin-proposal-object-rest-spread',
    '@babel/plugin-proposal-export-default-from',
  ],
  env: {
    test: {
      presets: [['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage' }]],
      plugins: ['babel-plugin-require-context-hook', 'babel-plugin-dynamic-import-node'],
    },
  },
  overrides: [
    {
      test: './examples/vue-kitchen-sink',
      presets: ['babel-preset-vue'],
    },
    {
      test: [
        './lib/core/src/server',
        './lib/node-logger',
        './lib/codemod',
        './addons/storyshots',
        './addons/storysource/src/loader',
        './app/**/src/server/**',
        './app/**/src/bin/**',
        './dangerfile.js',
      ],
      presets: [
        [
          '@babel/preset-env',
          {
            shippedProposals: true,
            useBuiltIns: 'usage',
            targets: {
              node: '8.11',
            },
          },
        ],
      ],
    },
  ],
};
<|endoftext|>


<commit_before>'use strict';

/* global before, after */

var Promise = require('bluebird'), partUtils = require('../utils'),
  Changes = require('../../../../../scripts/partitioner/sql/changes');

describe('offset', function () {

  var args = partUtils.init(this, beforeEach, afterEach, null, before, after);
  var testUtils = args.utils;

  var queueAndProcess = function (changes) {
    // Force quorum=true. We don't need to consider quorum when getting changes as only changes
    // recorded by quorum are added to LATEST and server downloads all changes regardless of quorum
    // status.
    return testUtils.queueAndProcess(args.db, changes, true);
  };

  it('should get changes by offset', function () {
    var changes = null,
      changes1 = [],
      changes2 = [],
      changes3 = [],
      up = (new Date()).toISOString();

    for (var i = 1; i <= 11; i++) {
      if (i > 10) {
        changes = changes3;
      } else if (i > 5) {
        changes = changes2;
      } else {
        changes = changes1;
      }
      changes.push({
        col: 'task',
        id: i + '',
        name: 'prority',
        val: '"low"',
        up: up
      });
    }

    // Note: to reliably ensure that changes are stored in particular order, we need to
    // queueAndProcess() and then sleep after adding each change
    var queueAndProcessEach = function (changes) {
      // Force quorum=true. We don't need to consider quorum when getting changes as only changes
      // recorded by quorum are added to LATEST and server downloads all changes regardless of quorum
      // status.
      return testUtils.queueAndProcessEach(args.db, changes, true);
    };

    return queueAndProcessEach(changes1).then(function () {
    }).then(function () {
      return queueAndProcessEach(changes2);
    }).then(function () {
      return args.db.changes(null, null, 5, 0);
    }).then(function (changes) {
      changes1.push('more'); // indicates more pages
      testUtils.changesShouldEql(changes1, changes);
    }).then(function () {
      return queueAndProcessEach(changes3); // simulate change between reads
    }).then(function () {
      return args.db.changes(null, null, 5, 5);
    }).then(function (changes) {
      changes2.push('more'); // indicates more pages
      testUtils.changesShouldEql(changes2, changes);
    }).then(function () {
      return args.db.changes(null, null, 5, 10);
    }).then(function (changes) {
      testUtils.changesShouldEql(changes3, changes);
    });
  });

  it('should throw error if limit too large', function () {
    return testUtils.shouldThrow(function () {
      return args.db.changes(null, null, Changes._MAX_LIMIT + 1);
    }, new Error('limit (' + (Changes._MAX_LIMIT + 1) + ') cannot be greater than ' +
      Changes._MAX_LIMIT));
  });

});<commit_msg>fix(offset): queueAndProcessEach<commit_after>'use strict';

/* global before, after */

var partUtils = require('../utils'),
  Changes = require('../../../../../scripts/partitioner/sql/changes');

describe('offset', function () {

  var args = partUtils.init(this, beforeEach, afterEach, null, before, after);
  var testUtils = args.utils;

  // Note: to reliably ensure that changes are stored in a particular order, we need to
  // queueAndProcess() and then sleep after adding each change
  var queueAndProcessEach = function (changes) {
    // Force quorum=true. We don't need to consider quorum when getting changes as only changes
    // recorded by quorum are added to LATEST and server downloads all changes regardless of quorum
    // status.
    return testUtils.queueAndProcessEach(args.db, changes, true);
  };

  it('should get changes by offset', function () {
    var changes = null,
      changes1 = [],
      changes2 = [],
      changes3 = [],
      up = (new Date()).toISOString();

    for (var i = 1; i <= 11; i++) {
      if (i > 10) {
        changes = changes3;
      } else if (i > 5) {
        changes = changes2;
      } else {
        changes = changes1;
      }
      changes.push({
        col: 'task',
        id: i + '',
        name: 'prority',
        val: '"low"',
        up: up
      });
    }

    return queueAndProcessEach(changes1).then(function () {
    }).then(function () {
      return queueAndProcessEach(changes2);
    }).then(function () {
      return args.db.changes(null, null, 5, 0);
    }).then(function (changes) {
      changes1.push('more'); // indicates more pages
      testUtils.changesShouldEql(changes1, changes);
    }).then(function () {
      return queueAndProcessEach(changes3); // simulate change between reads
    }).then(function () {
      return args.db.changes(null, null, 5, 5);
    }).then(function (changes) {
      changes2.push('more'); // indicates more pages
      testUtils.changesShouldEql(changes2, changes);
    }).then(function () {
      return args.db.changes(null, null, 5, 10);
    }).then(function (changes) {
      testUtils.changesShouldEql(changes3, changes);
    });
  });

  it('should throw error if limit too large', function () {
    return testUtils.shouldThrow(function () {
      return args.db.changes(null, null, Changes._MAX_LIMIT + 1);
    }, new Error('limit (' + (Changes._MAX_LIMIT + 1) + ') cannot be greater than ' +
      Changes._MAX_LIMIT));
  });

});<|endoftext|>


<commit_before>'use strict';

/* global describe, beforeEach, it, expect, inject */
describe('LocationModel.', function() {
    var Location;
    beforeEach(module('veganaut.app.map'));

    beforeEach(inject(function(_Location_) {
        Location = _Location_;
    }));

    it('is defined.', function() {
        expect(Location).toBeDefined();
        expect(typeof Location).toBe('function');
    });

    it('can be created from json.', function() {
        var loc = new Location({});
        expect(loc instanceof Location).toBe(true, 'created a Location object');
    });

    it('getUrl returns the correct URL.', function() {
        var loc = new Location({id: 'test1234'});
        expect(loc.getUrl()).toBe('/location/test1234', 'correct url');
        expect(loc.getUrl(true)).toBe('/location/test1234/edit', 'correct edit url');
    });

    describe('getRoundedQuality.', function() {
        it('returns correct default value.', function() {
            var loc = new Location();
            expect(loc.getRoundedQuality()).toBe(0);
        });

        it('rounds correctly.', function() {
            var loc = new Location({ quality: { average: 1.2 } });
            expect(loc.getRoundedQuality()).toBe(1, 'rounds down');
            loc = new Location({ quality: { average: 2.5 } });
            expect(loc.getRoundedQuality()).toBe(3, 'rounds up');
        });

        it('returns value between 0 and 5.', function() {
            var loc = new Location({ quality: { average: 7.3 } });
            expect(loc.getRoundedQuality()).toBe(5, 'max 5');
            loc = new Location({ quality: { average: -3.2 } });
            expect(loc.getRoundedQuality()).toBe(0, 'min 0');

        });
    });

    describe('setActive and isActive.', function() {
        it('returns correct default value.', function() {
            var loc = new Location();
            expect(typeof loc.isActive).toBe('function', 'isActive is a function');
            expect(typeof loc.setActive).toBe('function', 'setActive is a function');
            expect(loc.isActive()).toBe(false);
        });

        it('can be activated.', function() {
            var loc = new Location();
            loc.setActive();
            expect(loc.isActive()).toBe(true, 'default is to set active');

            loc = new Location();
            loc.setActive(true);
            expect(loc.isActive()).toBe(true, 'can explicitly set active');
        });

        it('can be activated and deactivated.', function() {
            var loc = new Location();
            loc.setActive();
            expect(loc.isActive()).toBe(true, 'set active');
            loc.setActive(false);
            expect(loc.isActive()).toBe(false, 'set inactive');
        });
    });

    describe('setDisabled and isDisabled.', function() {
        it('returns correct default value.', function() {
            var loc = new Location();
            expect(typeof loc.isDisabled).toBe('function', 'isDisabled is a function');
            expect(typeof loc.setDisabled).toBe('function', 'setDisabled is a function');
            expect(loc.isDisabled()).toBe(false);
        });

        it('can be set to hidden.', function() {
            var loc = new Location();
            loc.setDisabled();
            expect(loc.isDisabled()).toBe(true, 'default is to set hidden');

            loc = new Location();
            loc.setDisabled(true);
            expect(loc.isDisabled()).toBe(true, 'can explicitly set hidden');
        });

        it('can be hidden and shown.', function() {
            var loc = new Location();
            loc.setDisabled();
            expect(loc.isDisabled()).toBe(true, 'set hidden');
            loc.setDisabled(false);
            expect(loc.isDisabled()).toBe(false, 'set shown');
        });
    });

    describe('marker.', function() {
        it('instantiates a marker.', function() {
            var loc = new Location();
            var marker = loc.marker;
            expect(typeof marker).toBe('object', 'marker is an object');

            var icon = marker.options.icon.options;
            expect(typeof icon).toBe('object', 'icon is an object');
            expect(icon.iconSize).toBe(null, 'correct iconSize');
            expect(typeof icon.html).toBe('string', 'correct html type');
            expect(icon.className).toMatch(/\bmarker\b/, 'className contains "marker"');
        });

        it('added the location it on the marker.', function() {
            var loc = new Location({
                id: 'test123'
            });
            expect(loc.marker.locationId).toBe('test123');
        });

        it('updates marker icon className when changing active state.', function() {
            var loc = new Location();
            var icon = loc.marker.options.icon.options;
            var classRegex = /\bmarker--active\b/;
            expect(icon.className).toNotMatch(classRegex, 'does not have active class');
            loc.setActive();
            icon = loc.marker.options.icon.options;
            expect(icon.className).toMatch(classRegex, 'has active class when setting active');
            loc.setActive(false);
            icon = loc.marker.options.icon.options;
            expect(icon.className).toNotMatch(classRegex, 'active class removed when setting inactive');
        });

        it('updates marker icon className when changing disabled state.', function() {
            var loc = new Location();
            var icon = loc.marker.options.icon.options;
            var disabledClass = /\bmarker--disabled\b/;
            var enabledClass = /\bmarker--enabled\b/;
            expect(icon.className).toNotMatch(disabledClass, 'does not have the disabled class');
            expect(icon.className).toMatch(enabledClass, 'has the enabled class');
            loc.setDisabled();
            icon = loc.marker.options.icon.options;
            expect(icon.className).toMatch(disabledClass, 'has the disabled class when setting disabled');
            expect(icon.className).toNotMatch(enabledClass, 'does not have the enabled class when setting disabled');
            loc.setDisabled(false);
            icon = loc.marker.options.icon.options;
            expect(icon.className).toNotMatch(disabledClass, 'disabled class removed when setting enabled');
            expect(icon.className).toMatch(enabledClass, 'enabled class added when setting enabled');
        });
    });

    describe('setLatLng.', function() {
        it('method is defined.', function() {
            var loc = new Location();
            expect(typeof loc.setLatLng).toBe('function');
        });

        it('updates lat/lng of location and of marker.', function() {
            var loc = new Location({
                lat: 1,
                lng: 2
            });
            loc.setLatLng(3, 4);
            expect(loc.lat).toBe(3, 'set correct lat');
            expect(loc.lng).toBe(4, 'set correct lng');
            var markerLatLng = loc.marker.getLatLng();
            expect(markerLatLng.lat).toBe(3, 'set correct marker lat');
            expect(markerLatLng.lng).toBe(4, 'set correct marker lng');
        });
    });

    describe('getProductById.', function() {
        it('has method', function() {
            var loc = new Location();
            expect(typeof loc.getProductById).toBe('function', 'getProductById is a function');
            expect(typeof loc.getProductById('something')).toBe('undefined', 'returns undefined by default');
        });

        it('returns products by id', function() {
            var prod1 = {
                id: '123',
                name: 'thing'
            };
            var loc = new Location({
                products: [prod1]
            });

            expect(loc.getProductById('123')).toBe(prod1, 'finds product by id');
            expect(typeof loc.getProductById(123)).toBe('undefined', 'does strict matches');
            expect(typeof loc.getProductById('1234')).toBe('undefined', 'really checks id');
        });

        it('returns correct product with multiple products', function() {
            var prod1 = {
                id: '123',
                name: 'thing'
            };
            var prod2 = {
                id: '456',
                name: 'other'
            };
            var loc = new Location({
                products: [prod1, prod2]
            });

            expect(loc.getProductById('123')).toBe(prod1, 'finds prod1');
            expect(loc.getProductById('456')).toBe(prod2, 'finds prod2');
        });
    });

    describe('sanitiseLink.', function() {
        var loc;
        beforeEach(function() {
            loc = new Location();
        });

        it('method exists', function() {
            expect(typeof loc.sanitiseLink).toBe('function');
        });

        it('does not modify a valid link', function() {
            loc.link = 'http://example.com';
            loc.sanitiseLink();
            expect(loc.link).toBe('http://example.com', 'http link not modified');

            loc.link = 'https://www.bla.ch';
            loc.sanitiseLink();
            expect(loc.link).toBe('https://www.bla.ch', 'https link not modified');
        });

        it('adds http:// if not already there', function() {
            loc.link = 'example.com';
            loc.sanitiseLink();
            expect(loc.link).toBe('http://example.com', 'test 1');

            loc.link = 'a';
            loc.sanitiseLink();
            expect(loc.link).toBe('http://a', 'test 2');

            loc.link = 'ablahttp://';
            loc.sanitiseLink();
            expect(loc.link).toBe('http://ablahttp://', 'test 3');
        });

        it('does not modify empty link', function() {
            // Don't set any value
            loc.sanitiseLink();
            expect(typeof loc.link).toBe('undefined', 'test 1');

            loc.link = '';
            loc.sanitiseLink();
            expect(loc.link).toBe('', 'test 2');
        });
    });

    describe('getTypeIconClass static method.', function() {
        it('method exists', function() {
            expect(typeof Location.getIconClassForType).toBe('function');
        });

        it('returns false if no type given', function() {
            expect(Location.getIconClassForType()).toBe(false);
        });

        it('returns false if type is invalid', function() {
            expect(Location.getIconClassForType('bla')).toBe(false);
        });

        it('returns the correct icon per type', function() {
            expect(Location.getIconClassForType('gastronomy')).toBe('glyphicon glyphicon-cutlery');
            expect(Location.getIconClassForType('retail')).toBe('glyphicon glyphicon-shopping-cart');
        });
    });
});
<commit_msg>Fixing unit tests.<commit_after>'use strict';

/* global describe, beforeEach, it, expect, inject */
describe('LocationModel.', function() {
    var Location, playerService;
    beforeEach(module('veganaut.app.map'));

    beforeEach(module(function($provide) {
        // Set up all the mock dependencies
        playerService = {
            getImmediateMe: jasmine.createSpy('getImmediateMe')
        };

        $provide.value('playerService', playerService);
    }));

    beforeEach(inject(function(_Location_) {
        Location = _Location_;
    }));

    it('is defined.', function() {
        expect(Location).toBeDefined();
        expect(typeof Location).toBe('function');
    });

    it('can be created from json.', function() {
        var loc = new Location({});
        expect(loc instanceof Location).toBe(true, 'created a Location object');
    });

    it('getUrl returns the correct URL.', function() {
        var loc = new Location({id: 'test1234'});
        expect(loc.getUrl()).toBe('/location/test1234', 'correct url');
        expect(loc.getUrl(true)).toBe('/location/test1234/edit', 'correct edit url');
    });

    describe('getRoundedQuality.', function() {
        it('returns correct default value.', function() {
            var loc = new Location();
            expect(loc.getRoundedQuality()).toBe(0);
        });

        it('rounds correctly.', function() {
            var loc = new Location({ quality: { average: 1.2 } });
            expect(loc.getRoundedQuality()).toBe(1, 'rounds down');
            loc = new Location({ quality: { average: 2.5 } });
            expect(loc.getRoundedQuality()).toBe(3, 'rounds up');
        });

        it('returns value between 0 and 5.', function() {
            var loc = new Location({ quality: { average: 7.3 } });
            expect(loc.getRoundedQuality()).toBe(5, 'max 5');
            loc = new Location({ quality: { average: -3.2 } });
            expect(loc.getRoundedQuality()).toBe(0, 'min 0');

        });
    });

    describe('setActive and isActive.', function() {
        it('returns correct default value.', function() {
            var loc = new Location();
            expect(typeof loc.isActive).toBe('function', 'isActive is a function');
            expect(typeof loc.setActive).toBe('function', 'setActive is a function');
            expect(loc.isActive()).toBe(false);
        });

        it('can be activated.', function() {
            var loc = new Location();
            loc.setActive();
            expect(loc.isActive()).toBe(true, 'default is to set active');

            loc = new Location();
            loc.setActive(true);
            expect(loc.isActive()).toBe(true, 'can explicitly set active');
        });

        it('can be activated and deactivated.', function() {
            var loc = new Location();
            loc.setActive();
            expect(loc.isActive()).toBe(true, 'set active');
            loc.setActive(false);
            expect(loc.isActive()).toBe(false, 'set inactive');
        });
    });

    describe('setDisabled and isDisabled.', function() {
        it('returns correct default value.', function() {
            var loc = new Location();
            expect(typeof loc.isDisabled).toBe('function', 'isDisabled is a function');
            expect(typeof loc.setDisabled).toBe('function', 'setDisabled is a function');
            expect(loc.isDisabled()).toBe(false);
        });

        it('can be set to hidden.', function() {
            var loc = new Location();
            loc.setDisabled();
            expect(loc.isDisabled()).toBe(true, 'default is to set hidden');

            loc = new Location();
            loc.setDisabled(true);
            expect(loc.isDisabled()).toBe(true, 'can explicitly set hidden');
        });

        it('can be hidden and shown.', function() {
            var loc = new Location();
            loc.setDisabled();
            expect(loc.isDisabled()).toBe(true, 'set hidden');
            loc.setDisabled(false);
            expect(loc.isDisabled()).toBe(false, 'set shown');
        });
    });

    describe('marker.', function() {
        it('instantiates a marker.', function() {
            var loc = new Location();
            var marker = loc.marker;
            expect(typeof marker).toBe('object', 'marker is an object');

            var icon = marker.options.icon.options;
            expect(typeof icon).toBe('object', 'icon is an object');
            expect(icon.iconSize).toBe(null, 'correct iconSize');
            expect(typeof icon.html).toBe('string', 'correct html type');
            expect(icon.className).toMatch(/\bmarker\b/, 'className contains "marker"');
        });

        it('added the location it on the marker.', function() {
            var loc = new Location({
                id: 'test123'
            });
            expect(loc.marker.locationId).toBe('test123');
        });

        it('updates marker icon className when changing active state.', function() {
            var loc = new Location();
            var icon = loc.marker.options.icon.options;
            var classRegex = /\bmarker--active\b/;
            expect(icon.className).toNotMatch(classRegex, 'does not have active class');
            loc.setActive();
            icon = loc.marker.options.icon.options;
            expect(icon.className).toMatch(classRegex, 'has active class when setting active');
            loc.setActive(false);
            icon = loc.marker.options.icon.options;
            expect(icon.className).toNotMatch(classRegex, 'active class removed when setting inactive');
        });

        it('updates marker icon className when changing disabled state.', function() {
            var loc = new Location();
            var icon = loc.marker.options.icon.options;
            var disabledClass = /\bmarker--disabled\b/;
            var enabledClass = /\bmarker--enabled\b/;
            expect(icon.className).toNotMatch(disabledClass, 'does not have the disabled class');
            expect(icon.className).toMatch(enabledClass, 'has the enabled class');
            loc.setDisabled();
            icon = loc.marker.options.icon.options;
            expect(icon.className).toMatch(disabledClass, 'has the disabled class when setting disabled');
            expect(icon.className).toNotMatch(enabledClass, 'does not have the enabled class when setting disabled');
            loc.setDisabled(false);
            icon = loc.marker.options.icon.options;
            expect(icon.className).toNotMatch(disabledClass, 'disabled class removed when setting enabled');
            expect(icon.className).toMatch(enabledClass, 'enabled class added when setting enabled');
        });
    });

    describe('setLatLng.', function() {
        it('method is defined.', function() {
            var loc = new Location();
            expect(typeof loc.setLatLng).toBe('function');
        });

        it('updates lat/lng of location and of marker.', function() {
            var loc = new Location({
                lat: 1,
                lng: 2
            });
            loc.setLatLng(3, 4);
            expect(loc.lat).toBe(3, 'set correct lat');
            expect(loc.lng).toBe(4, 'set correct lng');
            var markerLatLng = loc.marker.getLatLng();
            expect(markerLatLng.lat).toBe(3, 'set correct marker lat');
            expect(markerLatLng.lng).toBe(4, 'set correct marker lng');
        });
    });

    describe('getProductById.', function() {
        it('has method', function() {
            var loc = new Location();
            expect(typeof loc.getProductById).toBe('function', 'getProductById is a function');
            expect(typeof loc.getProductById('something')).toBe('undefined', 'returns undefined by default');
        });

        it('returns products by id', function() {
            var prod1 = {
                id: '123',
                name: 'thing'
            };
            var loc = new Location({
                products: [prod1]
            });

            expect(loc.getProductById('123')).toBe(prod1, 'finds product by id');
            expect(typeof loc.getProductById(123)).toBe('undefined', 'does strict matches');
            expect(typeof loc.getProductById('1234')).toBe('undefined', 'really checks id');
        });

        it('returns correct product with multiple products', function() {
            var prod1 = {
                id: '123',
                name: 'thing'
            };
            var prod2 = {
                id: '456',
                name: 'other'
            };
            var loc = new Location({
                products: [prod1, prod2]
            });

            expect(loc.getProductById('123')).toBe(prod1, 'finds prod1');
            expect(loc.getProductById('456')).toBe(prod2, 'finds prod2');
        });
    });

    describe('sanitiseLink.', function() {
        var loc;
        beforeEach(function() {
            loc = new Location();
        });

        it('method exists', function() {
            expect(typeof loc.sanitiseLink).toBe('function');
        });

        it('does not modify a valid link', function() {
            loc.link = 'http://example.com';
            loc.sanitiseLink();
            expect(loc.link).toBe('http://example.com', 'http link not modified');

            loc.link = 'https://www.bla.ch';
            loc.sanitiseLink();
            expect(loc.link).toBe('https://www.bla.ch', 'https link not modified');
        });

        it('adds http:// if not already there', function() {
            loc.link = 'example.com';
            loc.sanitiseLink();
            expect(loc.link).toBe('http://example.com', 'test 1');

            loc.link = 'a';
            loc.sanitiseLink();
            expect(loc.link).toBe('http://a', 'test 2');

            loc.link = 'ablahttp://';
            loc.sanitiseLink();
            expect(loc.link).toBe('http://ablahttp://', 'test 3');
        });

        it('does not modify empty link', function() {
            // Don't set any value
            loc.sanitiseLink();
            expect(typeof loc.link).toBe('undefined', 'test 1');

            loc.link = '';
            loc.sanitiseLink();
            expect(loc.link).toBe('', 'test 2');
        });
    });

    describe('getIconClassForType static method.', function() {
        it('method exists', function() {
            expect(typeof Location.getIconClassForType).toBe('function');
        });

        it('returns false if no type given', function() {
            expect(Location.getIconClassForType()).toBe(false);
        });

        it('returns false if type is invalid', function() {
            expect(Location.getIconClassForType('bla')).toBe(false);
        });

        it('returns the correct icon per type', function() {
            expect(Location.getIconClassForType('gastronomy')).toBe('glyphicon glyphicon-cutlery');
            expect(Location.getIconClassForType('retail')).toBe('glyphicon glyphicon-shopping-cart');
        });
    });
});
<|endoftext|>


<commit_before>// FIXME: util
var WHITESPACE_CODEPOINTS = [
    // from WhiteSpace production
    0x0009,    // <TAB>
    0x000B,    // <VT>
    0x000C,    // <FF>
    0x0020,    // <SP>
    0x00A0,    // <NBSP>
    0xFEFF,    // <BOM>

    // WhiteSpace production also has <USP>, which means any other Unicode
    // space separator (category Zs), which needs to be checked from (up to
    // date) Unicode data.  The WhiteSpace-Z.txt file, created as part of
    // the build, currently contains (duplicates eliminated):

//  0x0020,    // 0020;SPACE;Zs;0;WS;;;;;N;;;;;
//  0x00A0,    // 00A0;NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;NON-BREAKING SPACE;;;;
    0x1680,    // 1680;OGHAM SPACE MARK;Zs;0;WS;;;;;N;;;;;
    0x180E,    // 180E;MONGOLIAN VOWEL SEPARATOR;Zs;0;WS;;;;;N;;;;;
    0x2000,    // 2000;EN QUAD;Zs;0;WS;2002;;;;N;;;;;
    0x2001,    // 2001;EM QUAD;Zs;0;WS;2003;;;;N;;;;;
    0x2002,    // 2002;EN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2003,    // 2003;EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2004,    // 2004;THREE-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2005,    // 2005;FOUR-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2006,    // 2006;SIX-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2007,    // 2007;FIGURE SPACE;Zs;0;WS;<noBreak> 0020;;;;N;;;;;
    0x2008,    // 2008;PUNCTUATION SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2009,    // 2009;THIN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x200A,    // 200A;HAIR SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
//  0x2028,    // 2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;;
//  0x2029,    // 2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;;
    0x202F,    // 202F;NARROW NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;;;;;
    0x205F,    // 205F;MEDIUM MATHEMATICAL SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x3000,    // 3000;IDEOGRAPHIC SPACE;Zs;0;WS;<wide> 0020;;;;N;;;;;

    // from LineTerminator production
    0x000a,    // <LF>
    0x000d,    // <CR>
    0x2028,    // <LS>
    0x2029,    // <PS>
];

/*===
string 3 foo
string 3 foo
string 3 foo
string 3 foo
===*/

function basicTest() {
    var all_ws;
    var i;

    function test(str) {
        var t;

        t = str.trim();
        print(typeof t, t.length, t);
    }

    all_ws = [];
    for (i = 0; i < WHITESPACE_CODEPOINTS; i++) {
        all_ws.push(String.fromCharCode(i));
    }
    all_ws = all_ws.join('');

    test('foo');
    test('  foo');
    test('foo  ');
    test(all_ws + 'foo' + all_ws);
}

try {
    basicTest();
} catch (e) {
    print(e);
}

<commit_msg>add coercion tests and fix a bug in String.prototype.trim() testcase<commit_after>// FIXME: util
var WHITESPACE_CODEPOINTS = [
    // from WhiteSpace production
    0x0009,    // <TAB>
    0x000B,    // <VT>
    0x000C,    // <FF>
    0x0020,    // <SP>
    0x00A0,    // <NBSP>
    0xFEFF,    // <BOM>

    // WhiteSpace production also has <USP>, which means any other Unicode
    // space separator (category Zs), which needs to be checked from (up to
    // date) Unicode data.  The WhiteSpace-Z.txt file, created as part of
    // the build, currently contains (duplicates eliminated):

//  0x0020,    // 0020;SPACE;Zs;0;WS;;;;;N;;;;;
//  0x00A0,    // 00A0;NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;NON-BREAKING SPACE;;;;
    0x1680,    // 1680;OGHAM SPACE MARK;Zs;0;WS;;;;;N;;;;;
    0x180E,    // 180E;MONGOLIAN VOWEL SEPARATOR;Zs;0;WS;;;;;N;;;;;
    0x2000,    // 2000;EN QUAD;Zs;0;WS;2002;;;;N;;;;;
    0x2001,    // 2001;EM QUAD;Zs;0;WS;2003;;;;N;;;;;
    0x2002,    // 2002;EN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2003,    // 2003;EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2004,    // 2004;THREE-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2005,    // 2005;FOUR-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2006,    // 2006;SIX-PER-EM SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2007,    // 2007;FIGURE SPACE;Zs;0;WS;<noBreak> 0020;;;;N;;;;;
    0x2008,    // 2008;PUNCTUATION SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x2009,    // 2009;THIN SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x200A,    // 200A;HAIR SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
//  0x2028,    // 2028;LINE SEPARATOR;Zl;0;WS;;;;;N;;;;;
//  0x2029,    // 2029;PARAGRAPH SEPARATOR;Zp;0;B;;;;;N;;;;;
    0x202F,    // 202F;NARROW NO-BREAK SPACE;Zs;0;CS;<noBreak> 0020;;;;N;;;;;
    0x205F,    // 205F;MEDIUM MATHEMATICAL SPACE;Zs;0;WS;<compat> 0020;;;;N;;;;;
    0x3000,    // 3000;IDEOGRAPHIC SPACE;Zs;0;WS;<wide> 0020;;;;N;;;;;

    // from LineTerminator production
    0x000a,    // <LF>
    0x000d,    // <CR>
    0x2028,    // <LS>
    0x2029,    // <PS>
];

/*===
basic
string 3 foo
string 3 foo
string 3 foo
string 3 foo
===*/

print('basic');

function basicTest() {
    var all_ws;
    var i;

    function test(str) {
        var t;

        t = str.trim();
        print(typeof t, t.length, t);
    }

    all_ws = [];
    for (i = 0; i < WHITESPACE_CODEPOINTS; i++) {
        all_ws.push(String.fromCharCode(WHITESPACE_CODEPOINTS[i]));
    }
    all_ws = all_ws.join('');

    test('foo');
    test('  foo');
    test('foo  ');
    test(all_ws + 'foo' + all_ws);
}

try {
    basicTest();
} catch (e) {
    print(e);
}

/*===
coercion
TypeError
TypeError
TypeError
string 4 true
string 5 false
string 3 123
string 3 foo
string 3 1,2
string 15 [object Object]
===*/

print('coercion');

function coercionTest() {
    function test(this_val, arg_count) {
        var t;

        try {
            if (arg_count == 0) {
                t = String.prototype.trim.call();
            } else {
                t = String.prototype.trim.call(this_val);
            }
            print(typeof t, t.length, t);
        } catch (e) {
            print(e.name);
        }
    }

    test(undefined, 0);
    test(undefined);
    test(null);
    test(true);
    test(false);
    test(123);
    test('foo');
    test([1,2]);
    test({ foo: 1, bar: 2 });
}

try {
    coercionTest();
} catch (e) {
    print(e);
}

<|endoftext|>