<commit_before>/**
 * Nested Records (SC.ChildRecord) Unit Test
 *
 * @author Evin Grano
 */

// ..........................................................
// Basic Set up needs to move to the setup and teardown
//
var NestedRecord, store, testParent, testParent2, childData1;

var initModels = function(){
  NestedRecord.ParentRecordTest = SC.Record.extend({
    /** Child Record Namespace */
    childRecordNamespace: NestedRecord,

    name: SC.Record.attr(String),
    info: SC.Record.toOne('NestedRecord.ChildRecordTest', { nested: true })
  });

  NestedRecord.ChildRecordTest = SC.ChildRecord.extend({
    id: SC.Record.attr(String),
    name: SC.Record.attr(String),
    value: SC.Record.attr(String)
  });
};

// ..........................................................
// Basic SC.Record Stuff
//
module("Basic SC.Record Functions w/ Parent > Child", {

  setup: function() {
    NestedRecord = SC.Object.create({
      store: SC.Store.create()
    });
    store = NestedRecord.store;
    initModels();
    SC.RunLoop.begin();
    // Test Parent 1
    testParent = store.createRecord(NestedRecord.ParentRecordTest, {
      name: 'Parent Name',
      info: {
        type: 'ChildRecordTest',
        name: 'Child Name',
        value: 'Blue Goo',
        id: '5001'
      }
    });
    // Test parent 2
    testParent2 = NestedRecord.store.createRecord(NestedRecord.ParentRecordTest, {
      name: 'Parent Name 2',
      info: {
        type: 'ChildRecordTest',
        name: 'Child Name 2',
        value: 'Purple Goo',
        id: '5002'
      }
    });
    SC.RunLoop.end();

    // ..........................................................
    // Child Data
    //
    childData1 = {
      type: 'ChildRecordTest',
      name: 'Child Name',
      value: 'Green Goo',
      id: '5002'
    };
  },

  teardown: function() {
    delete NestedRecord.ParentRecordTest;
    delete NestedRecord.ChildRecordTest;
    testParent = null;
    testParent2 = null;
    store = null;
    childData1 = null;
    NestedRecord = null;
  }
});

test("Function: readAttribute()", function() {
  equals(testParent.readAttribute('name'), 'Parent Name', "readAttribute should be correct for name attribute");

  equals(testParent.readAttribute('nothing'), null, "readAttribute should be correct for invalid key");

  same(testParent.readAttribute('info'),
    {
      type: 'ChildRecordTest',
      name: 'Child Name',
      value: 'Blue Goo',
      id: '5001'
    },
    "readAttribute should be correct for info child attribute");

});

test("Support Multiple Parent Records With Different Child Records", function() {

  same(testParent2.readAttribute('info'),
    {
      type: 'ChildRecordTest',
      name: 'Child Name 2',
      value: 'Purple Goo',
      id: '5002'
    },
    "readAttribute should be correct for info child attribute on new record");
  equals(testParent2.get('info').get('value'), 'Purple Goo', "get should retrieve the proper value on new record");

  same(testParent.readAttribute('info'),
    {
      type: 'ChildRecordTest',
      name: 'Child Name',
      value: 'Blue Goo',
      id: '5001'
    },
    "readAttribute should be correct for info child attribute on first record");
  equals(testParent.get('info').get('value'), 'Blue Goo', "get should retrieve the proper value on first record");
});

test("Function: writeAttribute()", function() {

  testParent.writeAttribute('name', 'New Parent Name');
  equals(testParent.get('name'), 'New Parent Name', "writeAttribute should be the new name attribute");

  testParent.writeAttribute('nothing', 'nothing');
  equals(testParent.get('nothing'), 'nothing', "writeAttribute should be correct for new key");

  testParent.writeAttribute('info', {
    type: 'ChildRecordTest',
    name: 'New Child Name',
    value: 'Red Goo'
  });
  same(testParent.readAttribute('info'),
    {
      type: 'ChildRecordTest',
      name: 'New Child Name',
      value: 'Red Goo'
    },
    "writeAttribute with readAttribute should be correct for info child attribute");
});

test("Basic Read", function() {
  var id;
  // Test general gets
  equals(testParent.get('name'), 'Parent Name', "get should be correct for name attribute");
  equals(testParent.get('nothing'), null, "get should be correct for invalid key");

  // Test Child Record creation
  var cr = testParent.get('info');
  // Check Model Class information
  ok(SC.kindOf(cr, SC.ChildRecord), "get() creates an actual instance that is a kind of a SC.ChildRecord Object");
  ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest), "get() creates an actual instance of a ChildRecordTest Object");

  // Check reference information
  var pm = cr.get('primaryKey');
  var key = cr.get(pm);
  var storeRef = store.find(NestedRecord.ChildRecordTest, key);
  ok(storeRef, 'checking that the store has the instance of the child record with proper primary key');
  equals(cr, storeRef, "checking the parent reference is the same as the direct store reference");

  // Check to see if the attributes of a Child Record match the refrence of the parent
  same(storeRef.get('attributes'), testParent.readAttribute('info'), "check that the ChildRecord's attributes are the same as the ParentRecord's readAttribute for the reference");

  // Duplication check
  var sameCR = testParent.get('info');
  ok(sameCR, "check to see if we have an instance of a child record again");
  var oldKey = cr.get(pm), newKey = sameCR.get(pm);
  equals(oldKey, newKey, "check to see if the Primary Key are the same");
  same(sameCR, cr, "check to see that it is the same child record as before");

  // ID check
  id = sameCR.get('id');
  ok((id !== oldKey), "if there is an id param, it should be different from the Primary Key: %@ != %@".fmt(id, oldKey));
});

test("Basic Write", function() {

  // Test general gets
  testParent.set('name', 'New Parent Name');
  equals(testParent.get('name'), 'New Parent Name', "set() should change name attribute");
  testParent.set('nothing', 'nothing');
  equals(testParent.get('nothing'), 'nothing', "set should change non-existent property to a new property");

  // Test Child Record creation
  var oldCR = testParent.get('info');
  testParent.set('info', {
    type: 'ChildRecordTest',
    name: 'New Child Name',
    value: 'Red Goo'
  });
  var cr = testParent.get('info');
  // Check Model Class information
  ok(SC.kindOf(cr, SC.ChildRecord), "set() with an object creates an actual instance that is a kind of a SC.ChildRecord Object");
  ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest), "set() with an object creates an actual instance of a ChildRecordTest Object");

  // Check reference information
  var pm = cr.get('primaryKey');
  var key = cr.get(pm);
  var storeRef = store.find(NestedRecord.ChildRecordTest, key);
  ok(storeRef, 'after a set() with an object, checking that the store has the instance of the child record with proper primary key');
  equals(cr, storeRef, "after a set with an object, checking the parent reference is the same as the direct store reference");
  var oldKey = oldCR.get(pm);
  ok(!(oldKey === key), 'check to see that the old child record has a different key from the new child record');

  // Check for changes on the child bubble to the parent.
  cr.set('name', 'Child Name Change');
  equals(cr.get('name'), 'Child Name Change', "after a set('name', <new>) on child, checking that the value is updated");
  ok(cr.get('status') & SC.Record.DIRTY, 'check that the child record is dirty');
  ok(testParent.get('status') & SC.Record.DIRTY, 'check that the parent record is dirty');
  var newCR = testParent.get('info');
  same(newCR, cr, "after a set('name', <new>) on child, checking to see that the parent has recieved the changes from the child record");
  same(testParent.readAttribute('info'), cr.get('attributes'), "after a set('name', <new>) on child, readAttribute on the parent should be correct for info child attributes");
});

test("Child Status Changed", function() {
  var cr;
  cr = testParent.get('info');
  equals(cr.get('status'), testParent.get('status'), 'after initializing the parent to READY_NEW, check that the child record matches');

  SC.RunLoop.begin();
  store.writeStatus(testParent.storeKey, SC.Record.DIRTY_NEW);
  store.dataHashDidChange(testParent.storeKey);
  equals(cr.get('status'), testParent.get('status'), 'after setting the parent to DIRTY_NEW, check that the child record matches');
  SC.RunLoop.end();

  SC.RunLoop.begin();
  store.writeStatus(testParent.storeKey, SC.Record.BUSY_REFRESH);
  store.dataHashDidChange(testParent.storeKey);
  equals(cr.get('status'), testParent.get('status'), 'after setting the parent to BUSY_REFRESH, check that the child record matches');
  SC.RunLoop.end();
});
<commit_msg>These tests fail because the store status for the child record is only updated when you 'get' the status of the child record. Notice that after cr.get('status') is called further tests matching the status pass.<commit_after>/**
 * Nested Records (SC.ChildRecord) Unit Test
 *
 * @author Evin Grano
 */

// ..........................................................
// Basic Set up needs to move to the setup and teardown
//
var NestedRecord, store, testParent, testParent2, childData1;

var initModels = function(){
  NestedRecord.ParentRecordTest = SC.Record.extend({
    /** Child Record Namespace */
    childRecordNamespace: NestedRecord,

    name: SC.Record.attr(String),
    info: SC.Record.toOne('NestedRecord.ChildRecordTest', { nested: true })
  });

  NestedRecord.ChildRecordTest = SC.ChildRecord.extend({
    id: SC.Record.attr(String),
    name: SC.Record.attr(String),
    value: SC.Record.attr(String)
  });
};

// ..........................................................
// Basic SC.Record Stuff
//
module("Basic SC.Record Functions w/ Parent > Child", {

  setup: function() {
    NestedRecord = SC.Object.create({
      store: SC.Store.create()
    });
    store = NestedRecord.store;
    initModels();
    SC.RunLoop.begin();
    // Test Parent 1
    testParent = store.createRecord(NestedRecord.ParentRecordTest, {
      name: 'Parent Name',
      info: {
        type: 'ChildRecordTest',
        name: 'Child Name',
        value: 'Blue Goo',
        id: '5001'
      }
    });
    // Test parent 2
    testParent2 = NestedRecord.store.createRecord(NestedRecord.ParentRecordTest, {
      name: 'Parent Name 2',
      info: {
        type: 'ChildRecordTest',
        name: 'Child Name 2',
        value: 'Purple Goo',
        id: '5002'
      }
    });
    SC.RunLoop.end();

    // ..........................................................
    // Child Data
    //
    childData1 = {
      type: 'ChildRecordTest',
      name: 'Child Name',
      value: 'Green Goo',
      id: '5002'
    };
  },

  teardown: function() {
    delete NestedRecord.ParentRecordTest;
    delete NestedRecord.ChildRecordTest;
    testParent = null;
    testParent2 = null;
    store = null;
    childData1 = null;
    NestedRecord = null;
  }
});

test("Function: readAttribute()", function() {
  equals(testParent.readAttribute('name'), 'Parent Name', "readAttribute should be correct for name attribute");

  equals(testParent.readAttribute('nothing'), null, "readAttribute should be correct for invalid key");

  same(testParent.readAttribute('info'),
    {
      type: 'ChildRecordTest',
      name: 'Child Name',
      value: 'Blue Goo',
      id: '5001'
    },
    "readAttribute should be correct for info child attribute");

});

test("Support Multiple Parent Records With Different Child Records", function() {

  same(testParent2.readAttribute('info'),
    {
      type: 'ChildRecordTest',
      name: 'Child Name 2',
      value: 'Purple Goo',
      id: '5002'
    },
    "readAttribute should be correct for info child attribute on new record");
  equals(testParent2.get('info').get('value'), 'Purple Goo', "get should retrieve the proper value on new record");

  same(testParent.readAttribute('info'),
    {
      type: 'ChildRecordTest',
      name: 'Child Name',
      value: 'Blue Goo',
      id: '5001'
    },
    "readAttribute should be correct for info child attribute on first record");
  equals(testParent.get('info').get('value'), 'Blue Goo', "get should retrieve the proper value on first record");
});

test("Function: writeAttribute()", function() {

  testParent.writeAttribute('name', 'New Parent Name');
  equals(testParent.get('name'), 'New Parent Name', "writeAttribute should be the new name attribute");

  testParent.writeAttribute('nothing', 'nothing');
  equals(testParent.get('nothing'), 'nothing', "writeAttribute should be correct for new key");

  testParent.writeAttribute('info', {
    type: 'ChildRecordTest',
    name: 'New Child Name',
    value: 'Red Goo'
  });
  same(testParent.readAttribute('info'),
    {
      type: 'ChildRecordTest',
      name: 'New Child Name',
      value: 'Red Goo'
    },
    "writeAttribute with readAttribute should be correct for info child attribute");
});

test("Basic Read", function() {
  var id;
  // Test general gets
  equals(testParent.get('name'), 'Parent Name', "get should be correct for name attribute");
  equals(testParent.get('nothing'), null, "get should be correct for invalid key");

  // Test Child Record creation
  var cr = testParent.get('info');
  // Check Model Class information
  ok(SC.kindOf(cr, SC.ChildRecord), "get() creates an actual instance that is a kind of a SC.ChildRecord Object");
  ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest), "get() creates an actual instance of a ChildRecordTest Object");

  // Check reference information
  var pm = cr.get('primaryKey');
  var key = cr.get(pm);
  var storeRef = store.find(NestedRecord.ChildRecordTest, key);
  ok(storeRef, 'checking that the store has the instance of the child record with proper primary key');
  equals(cr, storeRef, "checking the parent reference is the same as the direct store reference");

  // Check to see if the attributes of a Child Record match the refrence of the parent
  same(storeRef.get('attributes'), testParent.readAttribute('info'), "check that the ChildRecord's attributes are the same as the ParentRecord's readAttribute for the reference");

  // Duplication check
  var sameCR = testParent.get('info');
  ok(sameCR, "check to see if we have an instance of a child record again");
  var oldKey = cr.get(pm), newKey = sameCR.get(pm);
  equals(oldKey, newKey, "check to see if the Primary Key are the same");
  same(sameCR, cr, "check to see that it is the same child record as before");

  // ID check
  id = sameCR.get('id');
  ok((id !== oldKey), "if there is an id param, it should be different from the Primary Key: %@ != %@".fmt(id, oldKey));
});

test("Basic Write", function() {

  // Test general gets
  testParent.set('name', 'New Parent Name');
  equals(testParent.get('name'), 'New Parent Name', "set() should change name attribute");
  testParent.set('nothing', 'nothing');
  equals(testParent.get('nothing'), 'nothing', "set should change non-existent property to a new property");

  // Test Child Record creation
  var oldCR = testParent.get('info');
  testParent.set('info', {
    type: 'ChildRecordTest',
    name: 'New Child Name',
    value: 'Red Goo'
  });
  var cr = testParent.get('info');
  // Check Model Class information
  ok(SC.kindOf(cr, SC.ChildRecord), "set() with an object creates an actual instance that is a kind of a SC.ChildRecord Object");
  ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest), "set() with an object creates an actual instance of a ChildRecordTest Object");

  // Check reference information
  var pm = cr.get('primaryKey');
  var key = cr.get(pm);
  var storeRef = store.find(NestedRecord.ChildRecordTest, key);
  ok(storeRef, 'after a set() with an object, checking that the store has the instance of the child record with proper primary key');
  equals(cr, storeRef, "after a set with an object, checking the parent reference is the same as the direct store reference");
  var oldKey = oldCR.get(pm);
  ok(!(oldKey === key), 'check to see that the old child record has a different key from the new child record');

  // Check for changes on the child bubble to the parent.
  cr.set('name', 'Child Name Change');
  equals(cr.get('name'), 'Child Name Change', "after a set('name', <new>) on child, checking that the value is updated");
  ok(cr.get('status') & SC.Record.DIRTY, 'check that the child record is dirty');
  ok(testParent.get('status') & SC.Record.DIRTY, 'check that the parent record is dirty');
  var newCR = testParent.get('info');
  same(newCR, cr, "after a set('name', <new>) on child, checking to see that the parent has recieved the changes from the child record");
  same(testParent.readAttribute('info'), cr.get('attributes'), "after a set('name', <new>) on child, readAttribute on the parent should be correct for info child attributes");
});

test("Child Status Changed", function() {
  var cr;
  cr = testParent.get('info');
  equals(cr.get('status'), testParent.get('status'), 'after initializing the parent to READY_NEW, check that the child record matches');

  SC.RunLoop.begin();
  store.writeStatus(testParent.storeKey, SC.Record.READY_DIRTY);
  store.dataHashDidChange(testParent.storeKey);
  equals(cr.get('status'), testParent.get('status'), 'after setting the parent to READY_DIRTY, check that the child record matches');
  SC.RunLoop.end();

  SC.RunLoop.begin();
  store.writeStatus(testParent.storeKey, SC.Record.BUSY_REFRESH);
  store.dataHashDidChange(testParent.storeKey);
  equals(cr.get('status'), testParent.get('status'), 'after setting the parent to BUSY_REFRESH, check that the child record matches');
  SC.RunLoop.end();
});

test("Child Status Matches Store Status", function() {
  var cr;
  var storeStatus;
  cr = testParent.get('info');

  storeStatus = store.readStatus(cr.storeKey);
  equals(storeStatus, cr.get('status'), 'after initializing the parent to READY_NEW, check that the store status matches for the child');
  equals(cr.get('status'), testParent.get('status'), 'after initializing the parent to READY_NEW, check that the child record matches');

  SC.RunLoop.begin();
  store.writeStatus(testParent.storeKey, SC.Record.READY_CLEAN);
  store.dataHashDidChange(testParent.storeKey);
  SC.RunLoop.end();

  storeStatus = store.readStatus(cr.storeKey);
  equals(testParent.get('status'), SC.Record.READY_CLEAN, 'parent status should be READY_CLEAN');
  equals(storeStatus, cr.get('status'), 'after setting the parent to READY_CLEAN, the child\'s status and store status should be READY_CLEAN before calling get(\'status\') on the child');
  equals(cr.get('status'), testParent.get('status'), 'after setting the parent to READY_CLEAN, check that the child record matches');

  SC.RunLoop.begin();
  store.writeStatus(testParent.storeKey, SC.Record.READY_DIRTY);
  store.dataHashDidChange(testParent.storeKey);
  SC.RunLoop.end();

  storeStatus = store.readStatus(cr.storeKey);
  equals(testParent.get('status'), SC.Record.READY_DIRTY, 'parent status should be READY_DIRTY');
  equals(storeStatus, cr.get('status'), 'after setting the parent to READY_DIRTY, the child\'s status and store status should be READY_DIRTY before calling get(\'status\') on the child');
  equals(cr.get('status'), testParent.get('status'), 'after setting the parent to READY_DIRTY, check that the child record matches');

  SC.RunLoop.begin();
  store.writeStatus(testParent.storeKey, SC.Record.BUSY_REFRESH);
  store.dataHashDidChange(testParent.storeKey);
  storeStatus = store.readStatus(cr.storeKey);
  SC.RunLoop.end();

  equals(testParent.get('status'), SC.Record.BUSY_REFRESH, 'parent status should be BUSY_REFRESH');
  equals(storeStatus, cr.get('status'), 'after setting the parent to BUSY_REFRESH, the child\'s status and store status should be BUSY_REFRESH before calling get(\'status\') on the child');
  equals(cr.get('status'), testParent.get('status'), 'after setting the parent to BUSY_REFRESH, check that the child record matches');
});<|endoftext|>


<commit_before>describe("Geolocation RUBY API Test", function() {

	var timeout = false;

	beforeEach(function() {
		timeout = false;
	});

	it("should return current latitude of the device",function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getLatitude');

			// Time to wait ajax to be happen
			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should return current longitude of the device",function(){

		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getLongitude');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should return true if the location system is up and running, false otherwise.returns null if this feature is not supported on the device platform", function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getKnownPostion');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should return distance between Washington, D.C. and Moscow, Russia: expected  4856.99 miles using geolocation haversine_distance)",function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getHaversineDistance');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should return altitude in meters(meters above sea level)", function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getAltitude');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should return the speed if it is available(meters/sec over ground)", function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getSpeed');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should returns the estimated accuracy of the fix(Horizontal radius in Meters)", function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getAccuracy');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should returns the number of satellites used to determine the fix", function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getSatellitesCount');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should setnotification and callback should fired within 3 sec Interval", function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','setNotification');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

    if (["ANDROID"].indexOf(Rho.System.platform) != -1) {
		it("should setnotification EX and callback should fired within 3 sec Interval and Speed, altitude and satelite should be shown", function(){
			runs(function()
			{
				dispCurrentProcess(jasmine.getEnv().currentSpec.description);
				Ruby.call('Geolocation','setNotificationEX');

				setTimeout(function() {
					timeout = true;
				}, 2000);
			});

			waitsFor(function()
			{
				if(timeout == true)
					return true;
			}, 'Wait for 2 sec ajax call to happen', 3000);

			runs(function(){
				displayResult("Output: ",Ruby.getReturnedValue()+"
");
			});

			_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

		});
    }

});<commit_msg>Removed setnotification and setnotification ex code from spec and added in index.erb<commit_after>describe("Geolocation RUBY API Test", function() {

	var timeout = false;

	beforeEach(function() {
		timeout = false;
	});

	it("should return current latitude of the device",function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getLatitude');

			// Time to wait ajax to be happen
			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should return current longitude of the device",function(){

		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getLongitude');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should return true if the location system is up and running, false otherwise.returns null if this feature is not supported on the device platform", function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getKnownPostion');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should return distance between Washington, D.C. and Moscow, Russia: expected  4856.99 miles using geolocation haversine_distance)",function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getHaversineDistance');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should return altitude in meters(meters above sea level)", function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getAltitude');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should return the speed if it is available(meters/sec over ground)", function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getSpeed');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should returns the estimated accuracy of the fix(Horizontal radius in Meters)", function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getAccuracy');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});

	it("should returns the number of satellites used to determine the fix", function(){
		runs(function()
		{
			dispCurrentProcess(jasmine.getEnv().currentSpec.description);
			Ruby.call('Geolocation','getSatellitesCount');

			setTimeout(function() {
				timeout = true;
			}, 2000);
		});

		waitsFor(function()
		{
			if(timeout == true)
				return true;
		}, 'Wait for 2 sec ajax call to happen', 3000);

		runs(function(){
			displayResult("Output: ",Ruby.getReturnedValue()+"
");
		});

		_result.waitForResponse(); //Common Method implemented to wait for tester to make it pass or fail.Code available in specHelper.js

	});
});<|endoftext|>


<commit_before>'use strict';

angular.module('ehelseEditor').factory('Document', ['$rootScope', 'DocumentField', 'Topic', function($rootScope, DocumentField, Topic) {

    function newDocument() {
        return {
            id: null,
            timestamp: null,
            title: "",
            description: "",
            statusId: 1,
            sequence: 0,
            topicId: Topic.getSelected().id,
            comment: "",
            documentTypeId: "1",
            standardId: null,
            previousDocumentId: null,
            internalId: null,
            hisNumber: null,
            profiles: [],
            links: [],
            fields: [],
            targetGroups: [],
            populatedProfiles: []
        };
    }

    function newProfile(standardId) {
        return {
            id: null,
            timestamp: null,
            title: "",
            description: "",
            statusId: 1,
            sequence: 0,
            topicId: Topic.getSelected().id,
            comment: "",
            documentTypeId: "2",
            standardId: standardId,
            previousDocumentId: null,
            internalId: null,
            hisNumber: null,
            profiles: [],
            links: [],
            fields: [],
            targetGroups: [],
            populatedProfiles: []
        }
    }

    var current_document = newDocument();
    var topic_documents = [];
    var link_category_list = [];
    var documents = [];
    var documents_dict = {};
    var topics_documents_dict = {};

    function extendCurrentDocumentTargetGroupsByTargetGroupIds(target_groups_ids) {
        for (var i = 0; i < target_groups_ids.length; i++) {
            current_document.targetGroups.push({
                targetGroupId: target_groups_ids[i],
                description: "",
                actionId: null,
                deadline: "",
                mandatoryId: null
            });
        }
    }

    function extendCurrentDocumentFieldsByFieldIds(field_ids) {
        for (var i = 0; i < field_ids.length; i++) {
            current_document.fields.push({fieldId: field_ids[i], value: ""});
        }
    }

    function removeTargetGroup(group) {

        var index = current_document.targetGroups.indexOf(group);
        if (index > -1) {
            current_document.targetGroups.splice(index, 1);
        }
    }

    function removeField(field) {

        var index = current_document.fields.indexOf(field);
        if (index > -1) {
            current_document.fields.splice(index, 1);
        }
    }

    function removeCurrentDocumentLink(link) {

        var index = current_document.links.indexOf(link);
        if (index > -1) {
            current_document.links.splice(index, 1);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function submitCurrentDocument() {

        var populatedProfiles = [];
        Array.prototype.push.apply(populatedProfiles, current_document.populatedProfiles);
        current_document.populatedProfiles.length = 0;
        if (current_document.id) {

            $rootScope.put(
                'documents/' + current_document.id,
                current_document,
                function (data) {
                    updateDocumentInDocumentsList(data);
                    $rootScope.notifySuccess("Dokumentet ble oppdatert", 3000);
                    Array.prototype.push.apply(current_document.populatedProfiles, populatedProfiles);
                }
                ,
                function () {
                    $rootScope.notifyError("Dokumentet kunne ikke opprettes", 3000);
                }
            );
        }
        else {
            $rootScope.post(
                'documents/',
                current_document,
                function (data) {
                    data.populatedProfiles = [];
                    setCurrentDocument(data);
                    documents.push(data);
                    generateTopicsDocumentsDict(documents);
                    $rootScope.notifySuccess("Ny standard ble opprettet", 3000);
                    $rootScope.buttonState = 'editDocument';
                    Array.prototype.push.apply(current_document.populatedProfiles, populatedProfiles);
                }
                ,
                function () {
                    $rootScope.notifyError("Dokumentet kunne ikke opprettes", 3000);
                }
            );
        }
    }

    function deleteCurrentDocument() {
        $rootScope.delete(
            'documents/' + current_document.id,
            function(){
                deleteCurrentDocumentFromDocumentsList();
                $rootScope.notifySuccess("Dokumentet ble slettet", 5000);
                $rootScope.changeContentView('');
            },
            function(){
                console.log("Document could not be deleted");
                $rootScope.notifyError("Dokument kunne ikke bli slettet", 5000);
            }
        )
    }

    function getCurrentDocument() {
        return current_document;
    }

    function getTargetGroupsIdsHelper(targetGroups) {
        var ids = [];
        for (var i = 0; i < targetGroups.length; i++) {
            ids.push(targetGroups[i].targetGroupId);
        }
        return ids;
    }

    function getTargetGroupsIds() {
        return getTargetGroupsIdsHelper(current_document.targetGroups);
    }

    function updateDocumentInDocumentsList(document) {
        for (var i = 0; i < documents.length; i++) {
            if (documents[i].id == document.id) {
                setDocument(documents[i], document);
                break;
            }
        }
        generateTopicsDocumentsDict(documents);
    }

    function deleteCurrentDocumentFromDocumentsList() {
        for (var i = 0; i < documents.length; i++) {
            if (documents[i].id == current_document.id) {
                documents.splice(i,1);
                break;
            }
        }
        generateTopicsDocumentsDict(documents);
    }

    function getDocumentFieldIdsHelper(documentFields) {
        var ids = [];
        for (var i = 0; i < documentFields.length; i++) {
            ids.push(documentFields[i].fieldId);
        }
        return ids;
    }

    function getCurrentDocumentFieldIds() {
        return getDocumentFieldIdsHelper(current_document.fields);
    }

    function setDocument(a, b) {
        a.id = b.id;
        a.topicId = b.topicId;
        a.title = b.title;
        a.documentTypeId = b.documentTypeId;
        a.statusId = b.statusId;
        a.internalId = b.internalId;
        a.hisNumber = b.hisNumber;
        a.nextDocumentId = b.nextDocumentId;
        a.previousDocumentId = b.previousDocumentId;
        a.description = b.description;
        a.sequence = b.sequence;
        a.comment = b.comment;
        a.targetGroups = b.targetGroups;
        a.fields = b.fields;
        a.links = b.links;
        a.standardId = b.standardId;
        a.populatedProfiles = b.populatedProfiles || [];
    }

    function clone(document){
        var d = {};
        setDocument(d, document);
        return d;
    }

    function setCurrentDocument(document) {
        if (!document) {
            document = newDocument();
            setDocument(current_document, document);
            setCurrentDocumentFieldsByDocumentDocumentTypeId();
        }
        else {
            setDocument(current_document, document);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();

        if(document.standardId){
            getRelatedProfiles(document);
        }else{
            getProfiles(document)
        }
    }

    function getDocumentsByTopicId(id) {
        return topics_documents_dict[id];
    }

    function setCurrentDocumentFieldsByDocumentDocumentTypeId() {
        current_document.fields.length = 0;
        extendCurrentDocumentFieldsByFieldIds(DocumentField.getRequiredDocumentFieldIdsByDocumentTypeId(current_document.documentTypeId))
    }

    function generateCurrentDocumentLinksAsLinkCategoryList() {

        var link_category_dict = {};
        for (var i = 0; i < current_document.links.length; i++) {
            var link = current_document.links[i];
            if (!link_category_dict[link.linkCategoryId]) {
                link_category_dict[link.linkCategoryId] = {id: link.linkCategoryId, links: []};
            }
            link_category_dict[link.linkCategoryId].links.push(link);
        }
        link_category_list.length = 0;

        for (var prop in link_category_dict) {
            // skip loop if the property is from prototype
            if (!link_category_dict.hasOwnProperty(prop)) continue;

            link_category_list.push(link_category_dict[prop]);
        }
    }

    function getCurrentDocumentLinksAsLinkCategoryList() {
        return link_category_list;
    }

    function getCurrentDocumentLinkCategoriesIds() {
        var link_category_ids = [];
        for (var i = 0; i < current_document.links.length; i++) {
            link_category_ids.push(current_document.links[i].linkCategoryId);
        }
        return link_category_ids;
    }

    function extendCurrentDocumentLinkCategoriesByLinkCategoriesIds(ids) {
        for (var i = 0; i < ids.length; i++) {
            addLinkToCurrentDocumentByLinkCategoryId(ids[i]);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function addLinkToCurrentDocumentByLinkCategoryId(id) {
        current_document.links.push({linkCategoryId: id, text: "", url: ""});
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function removeCurrentDocumentLinksByCategoryId(linkCategoryId) {
        var tmp_list = [];
        for (var i = 0; i < current_document.links.length; i++) {
            if (current_document.links[i].linkCategoryId != linkCategoryId) {
                tmp_list.push(current_document.links[i]);
            }
        }
        current_document.links.length = 0;
        Array.prototype.push.apply(current_document.links, tmp_list);
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function getNewProfile(standardId) {
        return newProfile(standardId);
    }

    function getAllDocuments() {
        $rootScope.get(
            'documents/',
            function (data) {
                documents.length = 0;

                for(var i = 0; i < data.documents.length; i++){
                    var document = data.documents[i];
                    document.populatedProfiles = [];
                    documents.push(document);
                }

                generateDocumentDict(documents);
                generateTopicsDocumentsDict(documents);
            },
            function () {
                console.log("Could not load documents");
            }
        );
    }

    function newVersion(document){
        var new_version = clone(document);
        new_version.previousDocumentId = new_version.id;
        new_version.id = null;
        return new_version;
    }

    function generateDocumentDict(documents){
        for(var i = 0; i < documents.length; i++){
            documents_dict[documents[i].id] = documents[i];
        }
    }

    function generateTopicsDocumentsDict(documents){
        var topics = Topic.getAllAsDict();

        for(var id in topics) {
            if(Array.isArray(topics_documents_dict[id])){
                topics_documents_dict[id].length = 0;
            }
            else{
                topics_documents_dict[id] = [];
            }
        }

        var document;
        for(var i = 0; i < documents.length; i++){
            document = documents[i];
            if(!topics_documents_dict[document.topicId]){
                topics_documents_dict[document.topicId] = [];
            }
            topics_documents_dict[document.topicId].push(document);
        }
    }

    function getAll(){
        return documents;
    }

    function getProfiles(document) {

        var profiles = null;
        if(documents_dict[document.id]) {
            profiles = documents_dict[document.id].profiles;
        }

        if(profiles) {
            document.populatedProfiles.length = 0;
            for (var i = 0; i < profiles.length; i++) {
                document.populatedProfiles.push(documents_dict[profiles[i].id])
            }
        }
    }

    function getRelatedProfiles(document) {

        var profiles = null;
        if(documents_dict[document.standardId]) {
            profiles = documents_dict[document.standardId].profiles;
        }

        if(profiles) {
            document.populatedProfiles.length = 0;
            for (var i = 0; i < profiles.length; i++) {
                document.populatedProfiles.push(documents_dict[profiles[i].id])
            }
        }
    }

    getAllDocuments();

    function getAllAsDict(){
        return documents_dict;
    }

    function getById(id){
        return documents_dict[id];
    }

    return {
        getCurrentDocumentTargetGroupsIds: getTargetGroupsIds,
        getCurrentDocument: getCurrentDocument,
        extendCurrentDocumentTargetGroupsByTargetGroupIds: extendCurrentDocumentTargetGroupsByTargetGroupIds,
        removeCurrentDocumentTargetGroup: removeTargetGroup,
        submitCurrentDocument: submitCurrentDocument,
        setCurrentDocument: setCurrentDocument,
        getNewProfile: getNewProfile,
        newVersion: newVersion,
        getAll: getAll,
        getAllAsDict: getAllAsDict,
        getById: getById,
        deleteCurrentDocument: deleteCurrentDocument,
        getCurrentDocumentFieldIds: getCurrentDocumentFieldIds,
        extendCurrentDocumentFieldsByFieldIds: extendCurrentDocumentFieldsByFieldIds,
        removeCurrentDocumentField: removeField,
        getDocumentsByTopicId: getDocumentsByTopicId,
        setCurrentDocumentFieldsByDocumentDocumentTypeId: setCurrentDocumentFieldsByDocumentDocumentTypeId,
        getCurrentDocumentLinksAsLinkCategoryList: getCurrentDocumentLinksAsLinkCategoryList,
        getCurrentDocumentLinkCategoriesIds: getCurrentDocumentLinkCategoriesIds,
        extendCurrentDocumentLinkCategoriesByLinkCategoriesIds: extendCurrentDocumentLinkCategoriesByLinkCategoriesIds,
        addLinkToCurrentDocumentByLinkCategoryId: addLinkToCurrentDocumentByLinkCategoryId,
        removeCurrentDocumentLink: removeCurrentDocumentLink,
        removeCurrentDocumentLinksByCategoryId: removeCurrentDocumentLinksByCategoryId
    };
}]);
<commit_msg>New profile is added to list and selected<commit_after>'use strict';

angular.module('ehelseEditor').factory('Document', ['$rootScope', 'DocumentField', 'Topic', function($rootScope, DocumentField, Topic) {

    function newDocument() {
        return {
            id: null,
            timestamp: null,
            title: "",
            description: "",
            statusId: 1,
            sequence: 0,
            topicId: Topic.getSelected().id,
            comment: "",
            documentTypeId: "1",
            standardId: null,
            previousDocumentId: null,
            internalId: null,
            hisNumber: null,
            profiles: [],
            links: [],
            fields: [],
            targetGroups: [],
            populatedProfiles: []
        };
    }

    function newProfile(standardId) {
        return {
            id: null,
            timestamp: null,
            title: "",
            description: "",
            statusId: 1,
            sequence: 0,
            topicId: Topic.getSelected().id,
            comment: "",
            documentTypeId: "2",
            standardId: standardId,
            previousDocumentId: null,
            internalId: null,
            hisNumber: null,
            profiles: [],
            links: [],
            fields: [],
            targetGroups: [],
            populatedProfiles: []
        }
    }

    var current_document = newDocument();
    var topic_documents = [];
    var link_category_list = [];
    var documents = [];
    var documents_dict = {};
    var topics_documents_dict = {};

    function extendCurrentDocumentTargetGroupsByTargetGroupIds(target_groups_ids) {
        for (var i = 0; i < target_groups_ids.length; i++) {
            current_document.targetGroups.push({
                targetGroupId: target_groups_ids[i],
                description: "",
                actionId: null,
                deadline: "",
                mandatoryId: null
            });
        }
    }

    function extendCurrentDocumentFieldsByFieldIds(field_ids) {
        for (var i = 0; i < field_ids.length; i++) {
            current_document.fields.push({fieldId: field_ids[i], value: ""});
        }
    }

    function removeTargetGroup(group) {

        var index = current_document.targetGroups.indexOf(group);
        if (index > -1) {
            current_document.targetGroups.splice(index, 1);
        }
    }

    function removeField(field) {

        var index = current_document.fields.indexOf(field);
        if (index > -1) {
            current_document.fields.splice(index, 1);
        }
    }

    function removeCurrentDocumentLink(link) {

        var index = current_document.links.indexOf(link);
        if (index > -1) {
            current_document.links.splice(index, 1);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function submitCurrentDocument() {

        current_document.populatedProfiles.length = 0;
        if (current_document.id) {

            $rootScope.put(
                'documents/' + current_document.id,
                current_document,
                function (data) {
                    data.populatedProfiles = [];
                    setCurrentDocument(current_document);
                    updateDocumentInDocumentsList(data);
                    $rootScope.notifySuccess("Dokumentet ble oppdatert", 3000);
                }
                ,
                function () {
                    $rootScope.notifyError("Dokumentet kunne ikke opprettes", 3000);
                }
            );
        }
        else {
            $rootScope.post(
                'documents/',
                current_document,
                function (data) {
                    data.populatedProfiles = [];
                    //push profile id to standard
                    if(data.standardId){
                        documents_dict[data.standardId].profiles.push({id:data.id});
                        console.log(documents_dict[data.standardId].profiles);
                    }
                    documents.push(data);
                    generateDocumentDict(documents);
                    generateTopicsDocumentsDict(documents);
                    setCurrentDocument(data);
                    $rootScope.notifySuccess("Ny standard ble opprettet", 3000);
                    $rootScope.buttonState = 'editDocument';
                }
                ,
                function () {
                    $rootScope.notifyError("Dokumentet kunne ikke opprettes", 3000);
                }
            );
        }
    }

    function deleteCurrentDocument() {
        $rootScope.delete(
            'documents/' + current_document.id,
            function(){
                deleteCurrentDocumentFromDocumentsList();
                $rootScope.notifySuccess("Dokumentet ble slettet", 5000);
                $rootScope.changeContentView('');
            },
            function(){
                console.log("Document could not be deleted");
                $rootScope.notifyError("Dokument kunne ikke bli slettet", 5000);
            }
        )
    }

    function getCurrentDocument() {
        return current_document;
    }

    function getTargetGroupsIdsHelper(targetGroups) {
        var ids = [];
        for (var i = 0; i < targetGroups.length; i++) {
            ids.push(targetGroups[i].targetGroupId);
        }
        return ids;
    }

    function getTargetGroupsIds() {
        return getTargetGroupsIdsHelper(current_document.targetGroups);
    }

    function updateDocumentInDocumentsList(document) {
        for (var i = 0; i < documents.length; i++) {
            if (documents[i].id == document.id) {
                setDocument(documents[i], document);
                break;
            }
        }
        generateTopicsDocumentsDict(documents);
    }

    function deleteCurrentDocumentFromDocumentsList() {
        for (var i = 0; i < documents.length; i++) {
            if (documents[i].id == current_document.id) {
                documents.splice(i,1);
                break;
            }
        }
        generateTopicsDocumentsDict(documents);
    }

    function getDocumentFieldIdsHelper(documentFields) {
        var ids = [];
        for (var i = 0; i < documentFields.length; i++) {
            ids.push(documentFields[i].fieldId);
        }
        return ids;
    }

    function getCurrentDocumentFieldIds() {
        return getDocumentFieldIdsHelper(current_document.fields);
    }

    function setDocument(a, b) {
        a.id = b.id;
        a.topicId = b.topicId;
        a.title = b.title;
        a.documentTypeId = b.documentTypeId;
        a.statusId = b.statusId;
        a.internalId = b.internalId;
        a.hisNumber = b.hisNumber;
        a.nextDocumentId = b.nextDocumentId;
        a.previousDocumentId = b.previousDocumentId;
        a.description = b.description;
        a.sequence = b.sequence;
        a.comment = b.comment;
        a.targetGroups = b.targetGroups;
        a.fields = b.fields;
        a.links = b.links;
        a.standardId = b.standardId;
        a.populatedProfiles = b.populatedProfiles || [];
    }

    function clone(document){
        var d = {};
        setDocument(d, document);
        return d;
    }

    function setCurrentDocument(document) {
        if (!document) {
            document = newDocument();
            setDocument(current_document, document);
            setCurrentDocumentFieldsByDocumentDocumentTypeId();
        }
        else {
            setDocument(current_document, document);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();

        if(document.standardId){
            getRelatedProfiles(document);
        }else{
            getProfiles(document)
        }
    }

    function getDocumentsByTopicId(id) {
        return topics_documents_dict[id];
    }

    function setCurrentDocumentFieldsByDocumentDocumentTypeId() {
        current_document.fields.length = 0;
        extendCurrentDocumentFieldsByFieldIds(DocumentField.getRequiredDocumentFieldIdsByDocumentTypeId(current_document.documentTypeId))
    }

    function generateCurrentDocumentLinksAsLinkCategoryList() {

        var link_category_dict = {};
        for (var i = 0; i < current_document.links.length; i++) {
            var link = current_document.links[i];
            if (!link_category_dict[link.linkCategoryId]) {
                link_category_dict[link.linkCategoryId] = {id: link.linkCategoryId, links: []};
            }
            link_category_dict[link.linkCategoryId].links.push(link);
        }
        link_category_list.length = 0;

        for (var prop in link_category_dict) {
            // skip loop if the property is from prototype
            if (!link_category_dict.hasOwnProperty(prop)) continue;

            link_category_list.push(link_category_dict[prop]);
        }
    }

    function getCurrentDocumentLinksAsLinkCategoryList() {
        return link_category_list;
    }

    function getCurrentDocumentLinkCategoriesIds() {
        var link_category_ids = [];
        for (var i = 0; i < current_document.links.length; i++) {
            link_category_ids.push(current_document.links[i].linkCategoryId);
        }
        return link_category_ids;
    }

    function extendCurrentDocumentLinkCategoriesByLinkCategoriesIds(ids) {
        for (var i = 0; i < ids.length; i++) {
            addLinkToCurrentDocumentByLinkCategoryId(ids[i]);
        }
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function addLinkToCurrentDocumentByLinkCategoryId(id) {
        current_document.links.push({linkCategoryId: id, text: "", url: ""});
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function removeCurrentDocumentLinksByCategoryId(linkCategoryId) {
        var tmp_list = [];
        for (var i = 0; i < current_document.links.length; i++) {
            if (current_document.links[i].linkCategoryId != linkCategoryId) {
                tmp_list.push(current_document.links[i]);
            }
        }
        current_document.links.length = 0;
        Array.prototype.push.apply(current_document.links, tmp_list);
        generateCurrentDocumentLinksAsLinkCategoryList();
    }

    function getNewProfile(standardId) {
        return newProfile(standardId);
    }

    function getAllDocuments() {
        $rootScope.get(
            'documents/',
            function (data) {
                documents.length = 0;

                for(var i = 0; i < data.documents.length; i++){
                    var document = data.documents[i];
                    document.populatedProfiles = [];
                    documents.push(document);
                }

                generateDocumentDict(documents);
                generateTopicsDocumentsDict(documents);
            },
            function () {
                console.log("Could not load documents");
            }
        );
    }

    function newVersion(document){
        var new_version = clone(document);
        new_version.previousDocumentId = new_version.id;
        new_version.id = null;
        return new_version;
    }

    function generateDocumentDict(documents){
        for(var i = 0; i < documents.length; i++){
            documents_dict[documents[i].id] = documents[i];
        }
    }

    function generateTopicsDocumentsDict(documents){
        var topics = Topic.getAllAsDict();

        for(var id in topics) {
            if(Array.isArray(topics_documents_dict[id])){
                topics_documents_dict[id].length = 0;
            }
            else{
                topics_documents_dict[id] = [];
            }
        }

        var document;
        for(var i = 0; i < documents.length; i++){
            document = documents[i];
            if(!topics_documents_dict[document.topicId]){
                topics_documents_dict[document.topicId] = [];
            }
            topics_documents_dict[document.topicId].push(document);
        }
    }

    function getAll(){
        return documents;
    }

    function getProfiles(document) {

        var profiles = null;
        if(documents_dict[document.id]) {
            profiles = documents_dict[document.id].profiles;
        }

        if(profiles) {
            document.populatedProfiles.length = 0;
            for (var i = 0; i < profiles.length; i++) {
                document.populatedProfiles.push(documents_dict[profiles[i].id])
            }
        }
    }

    function getRelatedProfiles(document) {

        var profiles = null;
        if(documents_dict[document.standardId]) {
            profiles = documents_dict[document.standardId].profiles;
        }

        if(profiles) {
            document.populatedProfiles.length = 0;
            for (var i = 0; i < profiles.length; i++) {
                document.populatedProfiles.push(documents_dict[profiles[i].id])
            }
        }
    }

    getAllDocuments();

    function getAllAsDict(){
        return documents_dict;
    }

    function getById(id){
        return documents_dict[id];
    }

    return {
        getCurrentDocumentTargetGroupsIds: getTargetGroupsIds,
        getCurrentDocument: getCurrentDocument,
        extendCurrentDocumentTargetGroupsByTargetGroupIds: extendCurrentDocumentTargetGroupsByTargetGroupIds,
        removeCurrentDocumentTargetGroup: removeTargetGroup,
        submitCurrentDocument: submitCurrentDocument,
        setCurrentDocument: setCurrentDocument,
        getNewProfile: getNewProfile,
        newVersion: newVersion,
        getAll: getAll,
        getAllAsDict: getAllAsDict,
        getById: getById,
        deleteCurrentDocument: deleteCurrentDocument,
        getCurrentDocumentFieldIds: getCurrentDocumentFieldIds,
        extendCurrentDocumentFieldsByFieldIds: extendCurrentDocumentFieldsByFieldIds,
        removeCurrentDocumentField: removeField,
        getDocumentsByTopicId: getDocumentsByTopicId,
        setCurrentDocumentFieldsByDocumentDocumentTypeId: setCurrentDocumentFieldsByDocumentDocumentTypeId,
        getCurrentDocumentLinksAsLinkCategoryList: getCurrentDocumentLinksAsLinkCategoryList,
        getCurrentDocumentLinkCategoriesIds: getCurrentDocumentLinkCategoriesIds,
        extendCurrentDocumentLinkCategoriesByLinkCategoriesIds: extendCurrentDocumentLinkCategoriesByLinkCategoriesIds,
        addLinkToCurrentDocumentByLinkCategoryId: addLinkToCurrentDocumentByLinkCategoryId,
        removeCurrentDocumentLink: removeCurrentDocumentLink,
        removeCurrentDocumentLinksByCategoryId: removeCurrentDocumentLinksByCategoryId
    };
}]);
<|endoftext|>


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

var EXPORTED_SYMBOLS = ["BASE_PATH", "require", "unload", "_setupLoader"];

const {
  classes: Cc,
  interfaces: Ci,
  utils: Cu,
  results: Cr,
  Constructor: ctor,
  manager: Cm
} = Components;

const weak = Cu.getWeakReference.bind(Cu);
const reportError = Cu.reportError.bind(Cu);

Cm.QueryInterface(Ci.nsIComponentRegistrar);

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");

const lazy = XPCOMUtils.defineLazyGetter;

// hide our internals
// Since require() uses .scriptloader, the loaded require scopes will have
// access to the named stuff within this module scope, but we actually want
// them to have access to certain stuff.
(function setup_scope(exports) {
  Services = exports.Services = Object.create(Services);
  let dlsg = XPCOMUtils.defineLazyServiceGetter.bind(XPCOMUtils, Services);
  dlsg("catman", "@mozilla.org/categorymanager;1", "nsICategoryManager");
  dlsg("clipbrd", "@mozilla.org/widget/clipboard;1", "nsIClipboard");
  dlsg("drags", "@mozilla.org/widget/dragservice;1", "nsIDragService");
  dlsg("eps", "@mozilla.org/uriloader/external-protocol-service;1", "nsIExternalProtocolService");
  dlsg("fixups", "@mozilla.org/docshell/urifixup;1", "nsIURIFixup");
  dlsg("memrm", "@mozilla.org/memory-reporter-manager;1", "nsIMemoryReporterManager");
  dlsg("mime", "@mozilla.org/uriloader/external-helper-app-service;1", "nsIMIMEService");
  dlsg("mimeheader", "@mozilla.org/network/mime-hdrparam;1", "nsIMIMEHeaderParam");
  dlsg("uuid", "@mozilla.org/uuid-generator;1", "nsIUUIDGenerator");

  const Instances = exports.Instances = {
    get: function I_get(symbol, contract, iface, initializer) {
      if (!(symbol in this)) {
        this.register(symbol, contract, iface, initializer);
      }
      return this[symbol];
    },
    register: function I_register(symbol, contract, iface, initializer) {
      if (symbol in this) {
        let msg = "Symbol " + symbol + " already in Instances";
        log(LOG_ERROR, msg);
        throw new Error(msg);
      }
      if (initializer) {
        lazy(this, symbol, function() ctor(contract, iface, initializer));
        lazy(this, symbol + "_p", function() ctor(contract, iface));
      }
      else {
        lazy(this, symbol, function() ctor(contract, iface));
        lazy(this, symbol.toLowerCase(), function() new (ctor(contract, iface))());
      }
    }
  };

  const {SELF_PATH, BASE_PATH} = (function() {
    let rv;
    try { throw new Error("narf"); }
    catch (ex) {
      rv = {
        SELF_PATH: ex.fileName,
        BASE_PATH: /^(.+\/).*?$/.exec(ex.fileName)[1]
      };
    }
    return rv;
  })();
  exports.BASE_PATH = BASE_PATH;

  // logging stubs
  var log = function() {} // stub
  var LOG_DEBUG = 0, LOG_INFO = 0, LOG_ERROR = 0;

  var _unloaders = [];
  let _runUnloader = function _runUnloader(fn, args) {
      try {
        fn.apply(null, args);
      }
      catch (ex) {
        log(LOG_ERROR, "unloader failed", ex);
      }
  }
  exports.unload = function unload(fn) {
    if (fn == "shutdown") {
      log(LOG_INFO, "shutdown");
      for (let i = _unloaders.length; ~(--i);) {
        _runUnloader(_unloaders[i]);
      }
      _unloaders.splice(0);
      return;
    }

    // add an unloader
    if (typeof(fn) != "function") {
      throw new Error("unloader is not a function");
    }
    _unloaders.push(fn);
    return function() {
      _runUnloader(fn, arguments);
      _unloaders = _unloaders.filter(function(c) c != fn);
    };
  }

  const _registry = Object.create(null);
  exports.require = function require(module) {
    module = BASE_PATH + module + ".js";

    // already loaded?
    if (module in _registry) {
      return _registry[module];
    }

    // try to load the module
    log(LOG_DEBUG, "going to load: " + module);
    let scope = {exports: Object.create(null)};
    try {
      Services.scriptloader.loadSubScript(module, scope);
    }
    catch (ex) {
      log(LOG_ERROR, "failed to load " + module, ex);
      throw ex;
    }

    _registry[module] = scope.exports;
    log(LOG_DEBUG, "loaded module: " + module);

    return scope.exports;
  }
  exports.lazyRequire = function lazyRequire(module) {
    function lazyBind(props, prop) {
      log(LOG_DEBUG, "lazily binding " + props + " for module " + module);
      let m = require(module);
      for (let [,p] in Iterator(props)) {
        delete this[p];
        this[p] = m[p];
      }
      return this[prop];
    }

    // Already loaded?
    if (module in _registry) {
      log(LOG_DEBUG, "not lazily binding " + module + "; already loaded");
      return _registry[module];
    }

    let props = Array.slice(arguments, 1);
    let rv = {};
    let binder = lazyBind.bind(rv, props);
    for (let [,p] in Iterator(props)) {
      let _p = p;
      lazy(rv, _p, function() binder(_p));
    }
    return rv;
  }

  unload(function() {
    let keys = Object.keys(_registry);
    for (let i = keys.length; ~(--i);) {
      delete _registry[keys[i]];
    }
    // unload ourselves
    Cu.unload(SELF_PATH);
  });

  exports._setupLoader = function _setupLoader(data, callback) {
    delete exports._setupLoader;

    let _am = {};
    Cu.import("resource://gre/modules/AddonManager.jsm", _am);
    _am.AddonManager.getAddonByID(data.id, function loader_startup(addon) {
      exports.ADDON = addon;
      unload(function() delete exports.ADDON);

      let logging;
      try {
        logging = require("logging");
        for (let [k,v] in Iterator(logging)) {
          exports[k] = v;
        }

        let prefs = require("preferences");
        exports.prefs = prefs.prefs;
        exports.globalPrefs = prefs.globalPrefs;

        try {
          prefs.prefs.observe("loglevel",
            function(p,v) logging.setLogLevel(v),
            logging.LOG_NONE);
        }
        catch (ex) {
          logging.log(logging.LOG_ERROR, "failed to set log level", ex);
        }
      }
      catch (ex) {
        // probably do not have a working log() yet
        reportError(ex);
        return;
      }

      try {
        if (callback) {
          logging.log(logging.LOG_DEBUG, "loader: running callback");
          callback();
        }
      }
      catch (ex) {
        logging.log(logging.LOG_ERROR, "callback failed!", ex);
      }
      logging.log(logging.LOG_DEBUG, "loader: done");
    });
  }

})(this);

/* vim: set et ts=2 sw=2 : */
<commit_msg>Switch to a Cu.Sandbox module loader<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

var EXPORTED_SYMBOLS = ["BASE_PATH", "require", "unload", "_setupLoader"];

const {
  classes: Cc,
  interfaces: Ci,
  utils: Cu,
  results: Cr,
  Constructor: ctor,
  manager: Cm
} = Components;

const weak = Cu.getWeakReference.bind(Cu);
const reportError = Cu.reportError.bind(Cu);

Cm.QueryInterface(Ci.nsIComponentRegistrar);

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");

const lazy = XPCOMUtils.defineLazyGetter;

// hide our internals
// Since require() uses .scriptloader, the loaded require scopes will have
// access to the named stuff within this module scope, but we actually want
// them to have access to certain stuff.
(function setup_scope(exports) {
  Services = exports.Services = Object.create(Services);
  let dlsg = XPCOMUtils.defineLazyServiceGetter.bind(XPCOMUtils, Services);
  dlsg("catman", "@mozilla.org/categorymanager;1", "nsICategoryManager");
  dlsg("clipbrd", "@mozilla.org/widget/clipboard;1", "nsIClipboard");
  dlsg("drags", "@mozilla.org/widget/dragservice;1", "nsIDragService");
  dlsg("eps", "@mozilla.org/uriloader/external-protocol-service;1", "nsIExternalProtocolService");
  dlsg("fixups", "@mozilla.org/docshell/urifixup;1", "nsIURIFixup");
  dlsg("memrm", "@mozilla.org/memory-reporter-manager;1", "nsIMemoryReporterManager");
  dlsg("mime", "@mozilla.org/uriloader/external-helper-app-service;1", "nsIMIMEService");
  dlsg("mimeheader", "@mozilla.org/network/mime-hdrparam;1", "nsIMIMEHeaderParam");
  dlsg("sysprincipal", "@mozilla.org/systemprincipal;1", "nsIPrincipal");
  dlsg("uuid", "@mozilla.org/uuid-generator;1", "nsIUUIDGenerator");

  const Instances = exports.Instances = {
    get: function I_get(symbol, contract, iface, initializer) {
      if (!(symbol in this)) {
        this.register(symbol, contract, iface, initializer);
      }
      return this[symbol];
    },
    register: function I_register(symbol, contract, iface, initializer) {
      if (symbol in this) {
        let msg = "Symbol " + symbol + " already in Instances";
        log(LOG_ERROR, msg);
        throw new Error(msg);
      }
      if (initializer) {
        lazy(this, symbol, function() ctor(contract, iface, initializer));
        lazy(this, symbol + "_p", function() ctor(contract, iface));
      }
      else {
        lazy(this, symbol, function() ctor(contract, iface));
        lazy(this, symbol.toLowerCase(), function() new (ctor(contract, iface))());
      }
    }
  };

  const {SELF_PATH, BASE_PATH} = (function() {
    let rv;
    try { throw new Error("narf"); }
    catch (ex) {
      rv = {
        SELF_PATH: ex.fileName,
        BASE_PATH: /^(.+\/).*?$/.exec(ex.fileName)[1]
      };
    }
    return rv;
  })();
  exports.BASE_PATH = BASE_PATH;

  // logging stubs
  var log = function() {} // stub
  var LOG_DEBUG = 0, LOG_INFO = 0, LOG_ERROR = 0;

  var _unloaders = [];
  let _runUnloader = function _runUnloader(fn, args) {
      try {
        fn.apply(null, args);
      }
      catch (ex) {
        log(LOG_ERROR, "unloader failed", ex);
      }
  }
  exports.unload = function unload(fn) {
    if (fn == "shutdown") {
      log(LOG_INFO, "shutdown");
      for (let i = _unloaders.length; ~(--i);) {
        _runUnloader(_unloaders[i]);
      }
      _unloaders.splice(0);
      return;
    }

    // add an unloader
    if (typeof(fn) != "function") {
      throw new Error("unloader is not a function");
    }
    _unloaders.push(fn);
    return function() {
      _runUnloader(fn, arguments);
      _unloaders = _unloaders.filter(function(c) c != fn);
    };
  }

  const _registry = new Map();
  exports.require = function require(mod) {
    mod = BASE_PATH + mod + ".js";

    // already loaded?
    let scope = _registry.get(mod);
    if (scope) {
      return scope.exports;
    }

    // try to load the mod
    log(LOG_DEBUG, "going to load: " + mod);
    let scope = Object.create(exports);
    scope.exports = Object.create(null);
    try {
      scope = Cu.Sandbox(Services.sysprincipal, {
        sandboxName: mod,
        sandboxPrototype: scope,
        wantXRays: false
      });
      Services.scriptloader.loadSubScript(mod, scope);
    }
    catch (ex) {
      log(LOG_ERROR, "failed to load " + mod, ex);
      throw ex;
    }

    _registry.set(mod, scope);
    log(LOG_DEBUG, "loaded module: " + mod);

    return scope.exports;
  }
  exports.lazyRequire = function lazyRequire(mod) {
    function lazyBind(props, prop) {
      log(LOG_DEBUG, "lazily binding " + props + " for module " + mod);
      let m = require(mod);
      for (let [,p] in Iterator(props)) {
        delete this[p];
        this[p] = m[p];
      }
      return this[prop];
    }

    // Already loaded?
    let scope = _registry.get(mod);
    if (scope) {
      return scope.exports;
    }

    let props = Array.slice(arguments, 1);
    let rv = {};
    let binder = lazyBind.bind(rv, props);
    for (let [,p] in Iterator(props)) {
      let _p = p;
      lazy(rv, _p, function() binder(_p));
    }
    return rv;
  }

  unload(function() {
    for (let [mod, scope] of _registry) {
      _registry.delete(mod);
      Cu.nukeSandbox(scope);
    }
    if (_registry.clear) {
      _registry.clear();
    }
    // unload ourselves
    Cu.unload(SELF_PATH);
  });

  exports._setupLoader = function _setupLoader(data, callback) {
    delete exports._setupLoader;

    let _am = {};
    Cu.import("resource://gre/modules/AddonManager.jsm", _am);
    _am.AddonManager.getAddonByID(data.id, function loader_startup(addon) {
      exports.ADDON = addon;
      unload(function() delete exports.ADDON);

      let logging;
      try {
        logging = require("logging");
        for (let [k,v] in Iterator(logging)) {
          exports[k] = v;
        }

        let prefs = require("preferences");
        exports.prefs = prefs.prefs;
        exports.globalPrefs = prefs.globalPrefs;

        try {
          prefs.prefs.observe("loglevel",
            function(p,v) logging.setLogLevel(v),
            logging.LOG_NONE);
        }
        catch (ex) {
          logging.log(logging.LOG_ERROR, "failed to set log level", ex);
        }
      }
      catch (ex) {
        // probably do not have a working log() yet
        reportError(ex);
        return;
      }

      try {
        if (callback) {
          logging.log(logging.LOG_DEBUG, "loader: running callback");
          callback();
        }
      }
      catch (ex) {
        logging.log(logging.LOG_ERROR, "callback failed!", ex);
      }
      logging.log(logging.LOG_DEBUG, "loader: done");
    });
  }

})(this);

/* vim: set et ts=2 sw=2 : */
<|endoftext|>


<commit_before>import chai, { expect } from 'chai';
import { createStore } from 'redux';
import enhancer from '../src/enhancer';
import { batch, begin, end } from '../src/actions';

const action = (name) => ({ type: 'value', name });

const testReducer = (state = {}, action) => {
  return action.type === 'value'
    ? { ...state, [action.name]: true }
    : state;
};

const createEnhancedStore = (reducer) => {
  return createStore(
    reducer,
    enhancer
  );
};

describe('enhancer', () => {
  it('exposes redux api.', () => {
    const store = createEnhancedStore(() => {}),
          methods = Object.keys(store);

    expect(methods).to.have.length(4);
    expect(store.subscribe).to.be.a('function');
    expect(store.dispatch).to.be.a('function');
    expect(store.getState).to.be.a('function');
    expect(store.replaceReducer).to.be.a('function');
  });

  describe('dispatch', () => {
    it('explodes on raw batch dispatch.', () => {
      const store = createEnhancedStore(() => {});

      expect(
        () => store.dispatch(batch())
      ).to.throw();
    });

    it('passes through non batched actions.', () => {
      const reducer = chai.spy(testReducer),
            subscriber = chai.spy(),
            store = createEnhancedStore(reducer);

      reducer.reset();
      store.subscribe(subscriber);

      store.dispatch(action('a'));
      store.dispatch(action('b'));

      expect(subscriber).to.have.been.called.exactly(2);
      expect(reducer).to.have.been.called.exactly(2);
      expect(store.getState()).to.eql({
        a: true,
        b: true
      });
    });

    it('buffers batched actions.', () => {
      const reducer = chai.spy(testReducer),
            subscriber = chai.spy(),
            store = createEnhancedStore(reducer);

      reducer.reset();
      store.subscribe(subscriber);

      store.dispatch(begin());
      expect(subscriber).to.have.been.called.exactly(0);
      expect(reducer).to.have.been.called.exactly(0);

      store.dispatch(action('a'));
      store.dispatch(action('b'));
      expect(subscriber).to.have.been.called.exactly(0);
      expect(reducer).to.have.been.called.exactly(0);

      store.dispatch(end());
      expect(subscriber).to.have.been.called.exactly(1);
      expect(reducer).to.have.been.exactly(2);
      expect(store.getState()).to.eql({
        a: true,
        b: true
      });
    });

    it('buffers deep batches.', () => {
      const reducer = chai.spy(testReducer),
            subscriber = chai.spy(),
            store = createEnhancedStore(reducer);

      reducer.reset();
      store.subscribe(subscriber);

      [
        begin(),
        begin(),
        action('a'),
        action('b'),
        end(),
        action('c'),
        action('d'),
        begin(),
        end(),
        action('e'),
        end()
      ].forEach((action) => store.dispatch(action));
      expect(subscriber).to.have.been.called.exactly(1);
      expect(reducer).to.have.been.called.exactly(5);
      expect(store.getState()).to.eql({
        a: true,
        b: true,
        c: true,
        d: true,
        e: true
      });
    });
  });
});
<commit_msg>Add more tests<commit_after>import chai, { expect } from 'chai';
import { createStore } from 'redux';
import enhancer from '../src/enhancer';
import { batch, begin, end } from '../src/actions';

const action = (name) => ({ type: 'value', name });

const testReducer = (state = {}, action) => {
  return action.type === 'value'
    ? { ...state, [action.name]: true }
    : state;
};

const createEnhancedStore = (reducer) => {
  return createStore(
    reducer,
    enhancer
  );
};

describe('enhancer', () => {
  it('exposes redux api.', () => {
    const store = createEnhancedStore(() => {}),
          methods = Object.keys(store);

    expect(methods).to.have.length(4);
    expect(store.subscribe).to.be.a('function');
    expect(store.dispatch).to.be.a('function');
    expect(store.getState).to.be.a('function');
    expect(store.replaceReducer).to.be.a('function');
  });

  describe('dispatch', () => {
    it('explodes on raw batch dispatch.', () => {
      const store = createEnhancedStore(() => {});

      expect(
        () => store.dispatch(batch())
      ).to.throw();
    });

    it('passes through non batched actions.', () => {
      const reducer = chai.spy(testReducer),
            subscriber = chai.spy(),
            store = createEnhancedStore(reducer);

      reducer.reset();
      store.subscribe(subscriber);

      store.dispatch(action('a'));
      store.dispatch(action('b'));

      expect(subscriber).to.have.been.called.exactly(2);
      expect(reducer).to.have.been.called.exactly(2);
      expect(store.getState()).to.eql({
        a: true,
        b: true
      });
    });

    it('returns action results', () => {
      const store = createEnhancedStore(testReducer),
            result = store.dispatch(action('1'));

      expect(result).to.eql(action('1'));
    });

    it('buffers batched actions.', () => {
      const reducer = chai.spy(testReducer),
            subscriber = chai.spy(),
            store = createEnhancedStore(reducer);

      reducer.reset();
      store.subscribe(subscriber);

      store.dispatch(begin());
      expect(subscriber).to.have.been.called.exactly(0);
      expect(reducer).to.have.been.called.exactly(0);

      store.dispatch(action('a'));
      store.dispatch(action('b'));
      expect(subscriber).to.have.been.called.exactly(0);
      expect(reducer).to.have.been.called.exactly(0);

      store.dispatch(end());
      expect(subscriber).to.have.been.called.exactly(1);
      expect(reducer).to.have.been.exactly(2);
      expect(store.getState()).to.eql({
        a: true,
        b: true
      });
    });

    it('buffers deep batches.', () => {
      const reducer = chai.spy(testReducer),
            subscriber = chai.spy(),
            store = createEnhancedStore(reducer);

      reducer.reset();
      store.subscribe(subscriber);

      [
        begin(),
        begin(),
        action('a'),
        action('b'),
        end(),
        action('c'),
        action('d'),
        begin(),
        end(),
        action('e'),
        end()
      ].forEach((action) => store.dispatch(action));
      expect(subscriber).to.have.been.called.exactly(1);
      expect(reducer).to.have.been.called.exactly(5);
      expect(store.getState()).to.eql({
        a: true,
        b: true,
        c: true,
        d: true,
        e: true
      });
    });
  });
});
<|endoftext|>


<commit_before>import webpack from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import pug from 'pug'
import _debug from 'debug'

import config, {globals, paths, pkg, vendors} from '../config'

const {minimize} = config

const {__DEV__, NODE_ENV} = globals

const VUE_ENV = 'client'

const debug = _debug('hi:webpack:client')

debug(`create webpack configuration for NODE_ENV:${NODE_ENV}, VUE_ENV:${VUE_ENV}`)

import baseConfig from './base'

const clientConfig = {
  ...baseConfig,
  target: 'web',
  entry: {
    app: [paths.src('entry-client')],
    vendors
  },
  plugins: [
    ...baseConfig.plugins,
    new webpack.DefinePlugin({
      ...globals,
      __SERVER__: false
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendors',
      chunks: 'vendors'
    }),
    new HtmlWebpackPlugin({
      templateContent: pug.renderFile(paths.src('index.pug'), {
        pretty: !minimize,
        title: `${pkg.name} - ${pkg.description}`
      }),
      favicon: paths.src('static/favicon.ico'),
      hash: false,
      inject: true,
      minify: {
        collapseWhitespace: minimize,
        minifyJS: minimize
      }
    })
  ]
}

if (__DEV__) {
  debug('Enable plugins for live development (HMR, NoErrors).')

  clientConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin())
} else {
  debug(`Extract styles of app and bootstrap for ${NODE_ENV}.`)
}

export default clientConfig
<commit_msg>reduce bundle size<commit_after>import webpack from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import pug from 'pug'
import _debug from 'debug'

import config, {globals, paths, pkg, vendors} from '../config'

const {minimize} = config

const {__DEV__, NODE_ENV} = globals

const VUE_ENV = 'client'

const debug = _debug('hi:webpack:client')

debug(`create webpack configuration for NODE_ENV:${NODE_ENV}, VUE_ENV:${VUE_ENV}`)

import baseConfig from './base'

const clientConfig = {
  ...baseConfig,
  target: 'web',
  entry: {
    app: [paths.src('entry-client')],
    vendors
  },
  plugins: [
    ...baseConfig.plugins,
    new webpack.DefinePlugin({
      ...globals,
      __SERVER__: false
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendors'
    }),
    new HtmlWebpackPlugin({
      templateContent: pug.renderFile(paths.src('index.pug'), {
        pretty: !minimize,
        title: `${pkg.name} - ${pkg.description}`
      }),
      favicon: paths.src('static/favicon.ico'),
      hash: false,
      inject: true,
      minify: {
        collapseWhitespace: minimize,
        minifyJS: minimize
      }
    })
  ]
}

if (__DEV__) {
  debug('Enable plugins for live development (HMR, NoErrors).')

  clientConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin())
} else {
  debug(`Extract styles of app and bootstrap for ${NODE_ENV}.`)
}

export default clientConfig
<|endoftext|>


<commit_before>'use strict';

var mongo = require('mongodb').MongoClient;
module.exports = function(app) {

    app.get('/shorturl/new/*', function(req, res){
        var originalurl = req.url.split('/shorturl/new/')[1];
        mongo.connect(process.env.MONGO_URI, function(err, db){
            if (err) throw err;
            var collection = db.collection('urlcode');

            collection.find().toArray(function(err, arr){
                if (err) throw err;

                var code = arr[0].code;

                collection.update({}, {$set :{ 'code': code + 1 }});

                collection = db.collection('url');
                //console.log(req.connection.encrypted);
                var shurl = req.get('host') + "/shorturl/" + code;
                var shurljson;
                console.log( "**** " + req.headers['x-forwarded-proto']);
                if (req.connection.encrypted === undefined){
                    shurljson = "http://" + req.get('host') + "/shorturl/" + code;
                }
                else {
                    shurljson = "https://" + req.get('host') + "/shorturl/" + code;
                }
                var obj = {"original_url" : originalurl, "short_url": shurl};

                res.json({"original_url" : originalurl, "short_url": shurljson});

                collection.insert(obj, function(err){
                    if (err) throw err;
                    db.close();
                });
            });
        });
    });

    app.get('/shorturl/:code', function(req, res){
        var code = req.params.code;
        mongo.connect(process.env.MONGO_URI, function(err, db){
            if (err) throw err;
            var collection = db.collection('url');
            var short = req.get('host') + "/shorturl/" + code;
            collection.find({'short_url' : short}).toArray(function(err, arr){
                    if (err) throw err;
                    if (arr.length !== 0){
                        //console.log(arr[0].original_url);
                        res.redirect(arr[0].original_url);
                    }
                    else {
                        //console.log('Not found in database');
                        res.send('Not found in database');
                    }
                    db.close();
                });
        });
    });
}<commit_msg>Fix http https<commit_after>'use strict';

var mongo = require('mongodb').MongoClient;
module.exports = function(app) {

    app.get('/shorturl/new/*', function(req, res){
        var originalurl = req.url.split('/shorturl/new/')[1];
        mongo.connect(process.env.MONGO_URI, function(err, db){
            if (err) throw err;
            var collection = db.collection('urlcode');

            collection.find().toArray(function(err, arr){
                if (err) throw err;

                var code = arr[0].code;

                collection.update({}, {$set :{ 'code': code + 1 }});

                collection = db.collection('url');
                //console.log(req.connection.encrypted);
                var shurl = req.get('host') + "/shorturl/" + code;
                var shurljson = req.headers['x-forwarded-proto'] + "://" + shurl;
                var obj = {"original_url" : originalurl, "short_url": shurl};

                res.json({"original_url" : originalurl, "short_url": shurljson});

                collection.insert(obj, function(err){
                    if (err) throw err;
                    db.close();
                });
            });
        });
    });

    app.get('/shorturl/:code', function(req, res){
        var code = req.params.code;
        mongo.connect(process.env.MONGO_URI, function(err, db){
            if (err) throw err;
            var collection = db.collection('url');
            var short = req.get('host') + "/shorturl/" + code;
            collection.find({'short_url' : short}).toArray(function(err, arr){
                    if (err) throw err;
                    if (arr.length !== 0){
                        //console.log(arr[0].original_url);
                        res.redirect(arr[0].original_url);
                    }
                    else {
                        //console.log('Not found in database');
                        res.send('Not found in database');
                    }
                    db.close();
                });
        });
    });
}<|endoftext|>