<commit_before>'use strict';

const should = require('should');
const sinon = require('sinon');
const mockRequire = require('mock-require');
const {
  Request,
  PreconditionError,
  NotFoundError
} = require('../../../index');

const KuzzleMock = require('../../mocks/kuzzle.mock');
const MutexMock = require('../../mocks/mutex.mock.js');

const { NativeController } = require('../../../lib/api/controllers/baseController');

describe('AdminController', () => {
  let AdminController;
  let adminController;
  let kuzzle;
  let request;

  before(() => {
    mockRequire('../../../lib/util/mutex', { Mutex: MutexMock });
    AdminController = mockRequire.reRequire('../../../lib/api/controllers/adminController');
  });

  after(() => {
    mockRequire.stopAll();
  });

  beforeEach(() => {
    kuzzle = new KuzzleMock();

    adminController = new AdminController();

    request = new Request({ controller: 'admin' });

    request.input.args.refresh = 'wait_for';
  });

  describe('#constructor', () => {
    it('should inherit the base constructor', () => {
      should(adminController).instanceOf(NativeController);
    });
  });

  describe('#refreshIndexCache', () => {
    it('should trigger the corresponding event', async () => {
      await adminController.refreshIndexCache();

      should(kuzzle.ask)
        .be.calledWith('core:storage:public:cache:refresh');
    });
  });

  describe('#resetCache', () => {
    beforeEach(() => {
      request.input.action = 'resetCache';
    });

    it('should flush the cache for the public database', async () => {
      request.input.args.database = 'memoryStorage';

      await adminController.resetCache(request);

      should(kuzzle.ask).be.calledWith('core:cache:public:flushdb');
    });

    it('should flush the cache for the internal database', async () => {
      request.input.args.database = 'internalCache';

      await adminController.resetCache(request);

      should(kuzzle.ask).be.calledWith('core:cache:internal:flushdb');
    });

    it('should raise an error if database does not exist', () => {
      request.input.args.database = 'city17';

      return should(adminController.resetCache(request)).rejectedWith(
        NotFoundError,
        { id: 'services.cache.database_not_found' });
    });
  });

  describe('#resetSecurity', () => {
    beforeEach(() => {
      request.input.action = 'resetSecurity';
      kuzzle.internalIndex.createInitialSecurities.resolves({
        profileIds: ['anonymous', 'default', 'admin'],
        roleIds: ['anonymous', 'default', 'admin']
      });
    });

    it('should scroll and delete all registered users, profiles and roles', async () => {
      await adminController.resetSecurity(request);

      const userSpy = kuzzle.ask.withArgs('core:security:user:truncate');
      const profileSpy = kuzzle.ask.withArgs('core:security:profile:truncate');
      const roleSpy = kuzzle.ask.withArgs('core:security:role:truncate');
      should(kuzzle.internalIndex.createInitialSecurities)
        .be.calledOnce();

      sinon.assert.callOrder(
        userSpy,
        profileSpy,
        roleSpy,
        kuzzle.internalIndex.createInitialSecurities);

      const mutex = MutexMock.__getLastMutex();

      should(mutex.resource).eql('resetSecurity');
      should(mutex.timeout).eql(0);
      should(mutex.lock).calledOnce();
      should(mutex.unlock).calledOnce();
    });

    it('should unlock the action even if the promise rejects', async () => {
      request.input.args.refresh = 'wait_for';
      kuzzle.ask.withArgs('core:security:user:truncate').rejects();

      await should(adminController.resetSecurity(request)).be.rejected();

      const mutex1 = MutexMock.__getLastMutex();

      should(mutex1.resource).eql('resetSecurity');
      should(mutex1.timeout).eql(0);
      should(mutex1.lock).calledOnce();
      should(mutex1.unlock).calledOnce();

      kuzzle.ask.withArgs('core:security:user:truncate').resolves();

      await should(adminController.resetSecurity(request)).fulfilled();

      const mutex2 = MutexMock.__getLastMutex();

      should(mutex2.resource).eql('resetSecurity');
      should(mutex2.timeout).eql(0);
      should(mutex2.lock).calledOnce();
      should(mutex2.unlock).calledOnce();
      should(mutex2).not.eql(mutex1);
    });

    it('should reject if a security reset is already underway', async () => {
      MutexMock.__canLock(false);

      try {
        await should(adminController.resetSecurity(request))
          .rejectedWith(PreconditionError, { id: 'api.process.action_locked' });
        should(MutexMock.__getLastMutex().resource).eql('resetSecurity');
      }
      finally {
        MutexMock.__canLock(true);
      }
    });
  });

  describe('#resetDatabase', () => {
    beforeEach(() => {
      request.input.action = 'resetDatabase';
    });

    it('remove all indexes handled by Kuzzle', async () => {
      kuzzle.ask
        .withArgs('core:storage:public:index:list')
        .resolves(['a', 'b', 'c']);

      const response = await adminController.resetDatabase(request);

      should(kuzzle.ask).be.calledWith('core:storage:public:index:list');
      should(kuzzle.ask).be.calledWith(
        'core:storage:public:index:mDelete',
        ['a', 'b', 'c']);

      should(response).match({ acknowledge: true });

      const mutex = MutexMock.__getLastMutex();

      should(mutex.resource).eql('resetDatabase');
      should(mutex.timeout).eql(0);
      should(mutex.lock).calledOnce();
      should(mutex.unlock).calledOnce();
    });

    it('should reject if a database reset is already underway', async () => {
      MutexMock.__canLock(false);

      try {
        await should(adminController.resetDatabase(request))
          .rejectedWith(PreconditionError, { id: 'api.process.action_locked' });
        should(MutexMock.__getLastMutex().resource).eql('resetDatabase');
      }
      finally {
        MutexMock.__canLock(true);
      }
    });
  });

  describe('#dump', () => {
    it('should call kuzzle dump action', async () => {
      request.input.action = 'dump';
      request.input.args.suffix = 'dump-me-master';

      await adminController.dump(request);

      should(kuzzle.dump).be.calledOnce();
      should(kuzzle.dump.getCall(0).args[0]).be.eql('dump-me-master');
    });
  });

  describe('#shutdown', () => {
    beforeEach(() => {
      request.input.action = 'shutdown';
    });

    it('should throw an error if shutdown is in progress', async () => {
      adminController = new AdminController();
      adminController.shuttingDown = true;

      await should(adminController.shutdown(request))
        .rejectedWith(PreconditionError, { id: 'api.process.action_locked' });
    });

    it('should send invoke kuzzle.shutdown', async () => {
      await adminController.shutdown(request);

      should(kuzzle.shutdown).be.calledOnce();
    });
  });

  describe('#loadMappings', () => {
    beforeEach(() => {
      request.input.action = 'loadMappings';
      request.input.body = { city: { seventeen: {} } };
    });

    it('should call loadMappings from the public storage engine', async () => {
      await adminController.loadMappings(request);

      should(kuzzle.ask).be.calledWith(
        'core:storage:public:mappings:import',
        request.input.body);
    });
  });

  describe('#loadFixtures', () => {
    beforeEach(() => {
      request.input.action = 'loadFixtures';
      request.input.body = { city: { seventeen: [] } };
    });

    it('should call loadFixtures from the public storage engine', async () => {
      await adminController.loadFixtures(request);

      should(kuzzle.ask).be.calledWith(
        'core:storage:public:document:import',
        request.input.body);
    });

    it('should handle promise rejections when not waiting for a refresh', async () => {
      const err = new Error('err');

      kuzzle.ask
        .withArgs('core:storage:public:document:import')
        .rejects(err);

      request.input.args.refresh = false;

      await should(adminController.loadFixtures(request)).fulfilled();

      should(kuzzle.log.error).calledWith(err);
    });
  });

  describe('#loadSecurities', () => {
    beforeEach(() => {
      request.input.action = 'loadSecurities';
      request.input.args.onExistingUsers = 'overwrite';
      request.input.body = { gordon: { freeman: [] } };
    });

    it('should call loadSecurities from the secutiry module', async () => {
      await adminController.loadSecurities(request);

      should(kuzzle.ask)
        .be.calledOnce()
        .be.calledWith(
          'core:security:load',
          { gordon: { freeman: [] } },
          { onExistingUsers: 'overwrite', user: null, force: false });
    });
  });
});
<commit_msg>Fix adminController unit test<commit_after>'use strict';

const should = require('should');
const sinon = require('sinon');
const mockRequire = require('mock-require');
const {
  Request,
  PreconditionError,
  NotFoundError
} = require('../../../index');

const KuzzleMock = require('../../mocks/kuzzle.mock');
const MutexMock = require('../../mocks/mutex.mock.js');

const { NativeController } = require('../../../lib/api/controllers/baseController');

describe('AdminController', () => {
  let AdminController;
  let adminController;
  let kuzzle;
  let request;

  before(() => {
    mockRequire('../../../lib/util/mutex', { Mutex: MutexMock });
    AdminController = mockRequire.reRequire('../../../lib/api/controllers/adminController');
  });

  after(() => {
    mockRequire.stopAll();
  });

  beforeEach(() => {
    kuzzle = new KuzzleMock();

    adminController = new AdminController();

    request = new Request({ controller: 'admin' });

    request.input.args.refresh = 'wait_for';
  });

  describe('#constructor', () => {
    it('should inherit the base constructor', () => {
      should(adminController).instanceOf(NativeController);
    });
  });

  describe('#refreshIndexCache', () => {
    it('should trigger the corresponding event', async () => {
      await adminController.refreshIndexCache();

      should(kuzzle.ask)
        .be.calledWith('core:storage:public:cache:refresh');
    });
  });

  describe('#resetCache', () => {
    beforeEach(() => {
      request.input.action = 'resetCache';
    });

    it('should flush the cache for the public database', async () => {
      request.input.args.database = 'memoryStorage';

      await adminController.resetCache(request);

      should(kuzzle.ask).be.calledWith('core:cache:public:flushdb');
    });

    it('should flush the cache for the internal database', async () => {
      request.input.args.database = 'internalCache';

      await adminController.resetCache(request);

      should(kuzzle.ask).be.calledWith('core:cache:internal:flushdb');
    });

    it('should raise an error if database does not exist', () => {
      request.input.args.database = 'city17';

      return should(adminController.resetCache(request)).rejectedWith(
        NotFoundError,
        { id: 'services.cache.database_not_found' });
    });
  });

  describe('#resetSecurity', () => {
    beforeEach(() => {
      request.input.action = 'resetSecurity';
      kuzzle.internalIndex.createInitialSecurities.resolves({
        profileIds: ['anonymous', 'default', 'admin'],
        roleIds: ['anonymous', 'default', 'admin']
      });
    });

    it('should scroll and delete all registered users, profiles and roles', async () => {
      await adminController.resetSecurity(request);

      const userSpy = kuzzle.ask.withArgs('core:security:user:truncate');
      const profileSpy = kuzzle.ask.withArgs('core:security:profile:truncate');
      const roleSpy = kuzzle.ask.withArgs('core:security:role:truncate');
      should(kuzzle.internalIndex.createInitialSecurities)
        .be.calledOnce();

      sinon.assert.callOrder(
        userSpy,
        profileSpy,
        roleSpy,
        kuzzle.internalIndex.createInitialSecurities);

      const mutex = MutexMock.__getLastMutex();

      should(mutex.resource).eql('resetSecurity');
      should(mutex.timeout).eql(0);
      should(mutex.lock).calledOnce();
      should(mutex.unlock).calledOnce();
    });

    it('should unlock the action even if the promise rejects', async () => {
      request.input.args.refresh = 'wait_for';
      kuzzle.ask.withArgs('core:security:user:truncate').rejects();

      await should(adminController.resetSecurity(request)).be.rejected();

      const mutex1 = MutexMock.__getLastMutex();

      should(mutex1.resource).eql('resetSecurity');
      should(mutex1.timeout).eql(0);
      should(mutex1.lock).calledOnce();
      should(mutex1.unlock).calledOnce();

      kuzzle.ask.withArgs('core:security:user:truncate').resolves();

      await should(adminController.resetSecurity(request)).fulfilled();

      const mutex2 = MutexMock.__getLastMutex();

      should(mutex2.resource).eql('resetSecurity');
      should(mutex2.timeout).eql(0);
      should(mutex2.lock).calledOnce();
      should(mutex2.unlock).calledOnce();
      should(mutex2).not.eql(mutex1);
    });

    it('should reject if a security reset is already underway', async () => {
      MutexMock.__canLock(false);

      try {
        await should(adminController.resetSecurity(request))
          .rejectedWith(PreconditionError, { id: 'api.process.action_locked' });
        should(MutexMock.__getLastMutex().resource).eql('resetSecurity');
      }
      finally {
        MutexMock.__canLock(true);
      }
    });
  });

  describe('#resetDatabase', () => {
    beforeEach(() => {
      request.input.action = 'resetDatabase';
    });

    it('remove all indexes handled by Kuzzle', async () => {
      kuzzle.ask
        .withArgs('core:storage:public:index:list')
        .resolves(['a', 'b', 'c']);

      const response = await adminController.resetDatabase(request);

      should(kuzzle.ask).be.calledWith('core:storage:public:index:list');
      should(kuzzle.ask).be.calledWith(
        'core:storage:public:index:mDelete',
        ['a', 'b', 'c']);

      should(response).match({ acknowledge: true });

      const mutex = MutexMock.__getLastMutex();

      should(mutex.resource).eql('resetDatabase');
      should(mutex.timeout).eql(0);
      should(mutex.lock).calledOnce();
      should(mutex.unlock).calledOnce();
    });

    it('should reject if a database reset is already underway', async () => {
      MutexMock.__canLock(false);

      try {
        await should(adminController.resetDatabase(request))
          .rejectedWith(PreconditionError, { id: 'api.process.action_locked' });
        should(MutexMock.__getLastMutex().resource).eql('resetDatabase');
      }
      finally {
        MutexMock.__canLock(true);
      }
    });
  });

  describe('#dump', () => {
    it('should call kuzzle dump action', async () => {
      request.input.action = 'dump';
      request.input.args.suffix = 'dump-me-master';

      await adminController.dump(request);

      should(kuzzle.dump).be.calledOnce();
      should(kuzzle.dump.getCall(0).args[0]).be.eql('dump-me-master');
    });
  });

  describe('#shutdown', () => {
    beforeEach(() => {
      request.input.action = 'shutdown';
    });

    it('should throw an error if shutdown is in progress', async () => {
      adminController = new AdminController();
      adminController.shuttingDown = true;

      await should(adminController.shutdown(request))
        .rejectedWith(PreconditionError, { id: 'api.process.action_locked' });
    });

    it('should send invoke kuzzle.shutdown', async () => {
      await adminController.shutdown(request);

      should(kuzzle.shutdown).be.calledOnce();
    });
  });

  describe('#loadMappings', () => {
    beforeEach(() => {
      request.input.action = 'loadMappings';
      request.input.body = { city: { seventeen: {} } };
    });

    it('should call loadMappings from the public storage engine', async () => {
      await adminController.loadMappings(request);

      should(kuzzle.ask).be.calledWith(
        'core:storage:public:mappings:import',
        request.input.body);
    });
  });

  describe('#loadFixtures', () => {
    beforeEach(() => {
      request.input.action = 'loadFixtures';
      request.input.body = { city: { seventeen: [] } };
    });

    it('should call loadFixtures from the public storage engine', async () => {
      await adminController.loadFixtures(request);

      should(kuzzle.ask).be.calledWith(
        'core:storage:public:document:import',
        request.input.body);
    });

    it('should handle promise rejections when not waiting for a refresh', async () => {
      const err = new Error('err');

      kuzzle.ask
        .withArgs('core:storage:public:document:import')
        .rejects(err);

      request.input.args.refresh = false;

      await should(adminController.loadFixtures(request)).fulfilled();

      should(kuzzle.log.error).calledWith(err);
    });
  });

  describe('#loadSecurities', () => {
    beforeEach(() => {
      request.input.action = 'loadSecurities';
      request.input.args.onExistingUsers = 'overwrite';
      request.input.body = { gordon: { freeman: [] } };
    });

    it('should call loadSecurities from the secutiry module', async () => {
      await adminController.loadSecurities(request);

      should(kuzzle.ask)
        .be.calledOnce()
        .be.calledWith(
          'core:security:load',
          { gordon: { freeman: [] } },
          { onExistingUsers: 'overwrite', refresh: 'wait_for', user: null, force: false });
    });
  });
});
<|endoftext|>


<commit_before>var
  should = require('should'),
  RequestObject = require.main.require('kuzzle-common-objects').Models.requestObject,
  BadRequestError = require.main.require('kuzzle-common-objects').Errors.badRequestError,
  NotFoundError = require.main.require('kuzzle-common-objects').Errors.notFoundError,
  params = require('rc')('kuzzle'),
  Kuzzle = require.main.require('lib/api/Kuzzle');

describe('Test: hotelClerk.removeRooms', function () {
  var
    kuzzle,
    connection = {id: 'connectionid'},
    context,
    roomName,
    index = 'test',
    collection1 = 'user',
    collection2 = 'foo',
    filter1 = {
      term: {
        firstName: 'Ada'
      }
    },
    filter2 = {
      term: {
        name: 'foo'
      }
    };

  beforeEach(() => {
    kuzzle = new Kuzzle();

    return kuzzle.start(params, {dummy: true})
      .then(() => {
        context = {
          connection: connection,
          token: {
            user: ''
          }
        };
      });
  });

  it('should reject an error if no index provided', function () {
    var requestObject = new RequestObject({
      controller: 'admin',
      action: 'removeRooms',
      requestId: roomName,
      index: undefined,
      collection: collection1,
      body: {}
    });

    return should(kuzzle.hotelClerk.removeRooms(requestObject)).rejectedWith(BadRequestError);
  });

  it('should reject an error if no collection provided', function () {
    var requestObject = new RequestObject({
      controller: 'admin',
      action: 'removeRooms',
      requestId: roomName,
      index: index,
      collection: undefined,
      body: {}
    });

    return should(kuzzle.hotelClerk.removeRooms(requestObject)).rejectedWith(BadRequestError);
  });

  it('should reject an error if there is no subscription on this index', function () {
    var requestObject = new RequestObject({
      controller: 'admin',
      action: 'removeRooms',
      requestId: roomName,
      index: index,
      collection: collection1,
      body: {}
    });

    return should(kuzzle.hotelClerk.removeRooms(requestObject)).rejectedWith(NotFoundError);
  });

  it('should reject an error if there is no subscription on this collection', () => {
    var
      requestObjectSubscribe = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObject = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection2,
        body: {}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribe, context)
      .then(() => {
        return should(kuzzle.hotelClerk.removeRooms(requestObject)).rejectedWith(NotFoundError);
      });
  });

  it('should remove room in global subscription for provided collection', function () {
    var
      requestObjectSubscribe = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribe, context)
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(response => {
        should(response).have.property('acknowledge');
        should(response.acknowledge).be.true();

        should(kuzzle.hotelClerk.rooms).be.empty().Object();
        should(kuzzle.dsl.filters.filtersTree).be.empty().Object();
      });
  });

  it('should remove room for subscription with filter for provided collection', function () {
    var
      requestObjectSubscribe = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: filter1
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribe, context)
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(response => {
        should(response).have.property('acknowledge');
        should(response.acknowledge).be.true();

        should(kuzzle.hotelClerk.rooms).be.empty().Object();
        should(kuzzle.dsl.filters.filtersTree).be.empty().Object();
      });
  });

  it('should remove room for global and filter subscription provided collection', function () {
    var
      requestObjectSubscribeGlobal = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectSubscribeFilter = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: filter1
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribeGlobal, context)
      .then(() => kuzzle.hotelClerk.addSubscription(requestObjectSubscribeFilter, context))
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(response => {
        should(response).have.property('acknowledge');
        should(response.acknowledge).be.true();

        should(kuzzle.hotelClerk.rooms).be.empty().Object();
        should(kuzzle.dsl.filters.filtersTree).be.empty().Object();
      });
  });

  it('should remove only room for provided collection', function () {
    var
      requestObjectSubscribeCollection1 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectSubscribeCollection2 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection2,
        body: {}
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribeCollection1, context)
      .then(() => kuzzle.hotelClerk.addSubscription(requestObjectSubscribeCollection2, context))
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(response => {
        should(response).have.property('acknowledge');
        should(response.acknowledge).be.true();

        should(kuzzle.hotelClerk.rooms).be.Object();
        should(Object.keys(kuzzle.hotelClerk.rooms).length).be.exactly(1);

        should(kuzzle.dsl.filters.filtersTree).be.Object();
        should(Object.keys(kuzzle.dsl.filters.filtersTree).length).be.exactly(1);
        should(Object.keys(kuzzle.dsl.filters.filtersTree[index]).length).be.exactly(1);
        should(kuzzle.dsl.filters.filtersTree[index][collection1]).be.undefined();
        should(kuzzle.dsl.filters.filtersTree[index][collection2]).be.Object();
      });
  });

  it('should reject an error if room is provided but is not an array', function () {
    var
      requestObjectSubscribeCollection1 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {rooms: {}}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribeCollection1, context)
      .then(() => {
        return should(kuzzle.hotelClerk.removeRooms(requestObjectRemove)).be.rejectedWith(BadRequestError);
      });
  });

  it('should remove only listed rooms for the collection', function () {
    var
      roomId = 'fa2dc987b065e6d38beadabc970d92f1',
      requestObjectSubscribeFilter1 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomId,
        index: index,
        collection: collection1,
        body: filter1
      }),
      requestObjectSubscribeFilter2 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomId,
        index: index,
        collection: collection1,
        body: filter2
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomId,
        index: index,
        collection: collection1,
        body: {rooms: [roomId]}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribeFilter1, context)
      .then(() => kuzzle.hotelClerk.addSubscription(requestObjectSubscribeFilter2, context))
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(() => {
        should(Object.keys(kuzzle.hotelClerk.rooms).length).be.exactly(1);
        should(kuzzle.hotelClerk.rooms[roomName]).be.undefined();
      });
  });

  it('should return a response with partial error if a roomId doesn\'t correspond to the collection', function () {
    var
      badRoomName = '0ca6c2f9b4cc6450a63e3fe848ec7138',
      requestObjectSubscribe1 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectSubscribe2 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection2,
        body: {}
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {rooms: [badRoomName]}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribe1, context)
      .then(() => kuzzle.hotelClerk.addSubscription(requestObjectSubscribe2, context))
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then((response) => {
        should(response.acknowledge).be.true();
        should(response.partialErrors.length).be.exactly(1);
        should(response.partialErrors).be.an.Array().and.match([`No room with id ${badRoomName}`]);
      });
  });

  it('should return a response with partial error if a roomId doesn\'t exist', function () {
    var
      badRoomName = 'badRoomId',
      requestObjectSubscribe = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {rooms: [badRoomName]}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribe, context)
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(response => {
        should(response.acknowledge).be.true();
        should(response.partialErrors.length).be.exactly(1);
        should(response.partialErrors).be.an.Array().and.match(['No room with id ' + badRoomName]);
      });
  });
});
<commit_msg>fixed hotelClerk.removeRooms tests<commit_after>var
  should = require('should'),
  RequestObject = require.main.require('kuzzle-common-objects').Models.requestObject,
  BadRequestError = require.main.require('kuzzle-common-objects').Errors.badRequestError,
  NotFoundError = require.main.require('kuzzle-common-objects').Errors.notFoundError,
  params = require('rc')('kuzzle'),
  Kuzzle = require.main.require('lib/api/Kuzzle');

describe('Test: hotelClerk.removeRooms', function () {
  var
    kuzzle,
    connection = {id: 'connectionid'},
    context,
    roomName,
    index = 'test',
    collection1 = 'user',
    collection2 = 'foo',
    filter1 = {
      term: {
        firstName: 'Ada'
      }
    },
    filter2 = {
      term: {
        name: 'foo'
      }
    };

  beforeEach(() => {
    kuzzle = new Kuzzle();

    return kuzzle.start(params, {dummy: true})
      .then(() => {
        context = {
          connection: connection,
          token: {
            user: ''
          }
        };
      });
  });

  it('should reject an error if no index provided', function () {
    var requestObject = new RequestObject({
      controller: 'admin',
      action: 'removeRooms',
      requestId: roomName,
      index: undefined,
      collection: collection1,
      body: {}
    });

    return should(kuzzle.hotelClerk.removeRooms(requestObject)).rejectedWith(BadRequestError);
  });

  it('should reject an error if no collection provided', function () {
    var requestObject = new RequestObject({
      controller: 'admin',
      action: 'removeRooms',
      requestId: roomName,
      index: index,
      collection: undefined,
      body: {}
    });

    return should(kuzzle.hotelClerk.removeRooms(requestObject)).rejectedWith(BadRequestError);
  });

  it('should reject an error if there is no subscription on this index', function () {
    var requestObject = new RequestObject({
      controller: 'admin',
      action: 'removeRooms',
      requestId: roomName,
      index: index,
      collection: collection1,
      body: {}
    });

    return should(kuzzle.hotelClerk.removeRooms(requestObject)).rejectedWith(NotFoundError);
  });

  it('should reject an error if there is no subscription on this collection', () => {
    var
      requestObjectSubscribe = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObject = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection2,
        body: {}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribe, context)
      .then(() => {
        return should(kuzzle.hotelClerk.removeRooms(requestObject)).rejectedWith(NotFoundError);
      });
  });

  it('should remove room in global subscription for provided collection', function () {
    var
      requestObjectSubscribe = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribe, context)
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(response => {
        should(response).have.property('acknowledge');
        should(response.acknowledge).be.true();

        should(kuzzle.hotelClerk.rooms).be.empty().Object();
        should(kuzzle.dsl.filters.filtersTree).be.empty().Object();
      });
  });

  it('should remove room for subscription with filter for provided collection', function () {
    var
      requestObjectSubscribe = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: filter1
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribe, context)
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(response => {
        should(response).have.property('acknowledge');
        should(response.acknowledge).be.true();

        should(kuzzle.hotelClerk.rooms).be.empty().Object();
        should(kuzzle.dsl.filters.filtersTree).be.empty().Object();
      });
  });

  it('should remove room for global and filter subscription provided collection', function () {
    var
      requestObjectSubscribeGlobal = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectSubscribeFilter = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: filter1
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribeGlobal, context)
      .then(() => kuzzle.hotelClerk.addSubscription(requestObjectSubscribeFilter, context))
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(response => {
        should(response).have.property('acknowledge');
        should(response.acknowledge).be.true();

        should(kuzzle.hotelClerk.rooms).be.empty().Object();
        should(kuzzle.dsl.filters.filtersTree).be.empty().Object();
      });
  });

  it('should remove only room for provided collection', function () {
    var
      requestObjectSubscribeCollection1 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectSubscribeCollection2 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection2,
        body: {}
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribeCollection1, context)
      .then(() => kuzzle.hotelClerk.addSubscription(requestObjectSubscribeCollection2, context))
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(response => {
        should(response).have.property('acknowledge');
        should(response.acknowledge).be.true();

        should(kuzzle.hotelClerk.rooms).be.Object();
        should(Object.keys(kuzzle.hotelClerk.rooms).length).be.exactly(1);

        should(kuzzle.dsl.filters.filtersTree).be.Object();
        should(Object.keys(kuzzle.dsl.filters.filtersTree).length).be.exactly(1);
        should(Object.keys(kuzzle.dsl.filters.filtersTree[index]).length).be.exactly(1);
        should(kuzzle.dsl.filters.filtersTree[index][collection1]).be.undefined();
        should(kuzzle.dsl.filters.filtersTree[index][collection2]).be.Object();
      });
  });

  it('should reject an error if room is provided but is not an array', function () {
    var
      requestObjectSubscribeCollection1 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {rooms: {}}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribeCollection1, context)
      .then(() => {
        return should(kuzzle.hotelClerk.removeRooms(requestObjectRemove)).be.rejectedWith(BadRequestError);
      });
  });

  it('should remove only listed rooms for the collection', function () {
    var
      roomId = 'fa2dc987b065e6d38beadabc970d92f1',
      requestObjectSubscribeFilter1 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomId,
        index: index,
        collection: collection1,
        body: filter1
      }),
      requestObjectSubscribeFilter2 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomId,
        index: index,
        collection: collection1,
        body: filter2
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomId,
        index: index,
        collection: collection1,
        body: {rooms: [roomId]}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribeFilter1, context)
      .then(() => kuzzle.hotelClerk.addSubscription(requestObjectSubscribeFilter2, context))
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(() => {
        should(Object.keys(kuzzle.hotelClerk.rooms).length).be.exactly(1);
        should(kuzzle.hotelClerk.rooms[roomName]).be.undefined();
      });
  });

  it('should return a response with partial error if a roomId doesn\'t correspond to the index', function () {
    var
      index2RoomName = 'e6255f81a2934ad02636a8ebf533dd46',
      requestObjectSubscribe1 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectSubscribe2 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        index: 'index2',
        collection: collection1,
        body: {}
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {rooms: [index2RoomName]}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribe1, context)
      .then(() => kuzzle.hotelClerk.addSubscription(requestObjectSubscribe2, context))
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then((response) => {
        should(response.acknowledge).be.true();
        should(response.partialErrors.length).be.exactly(1);
        should(response.partialErrors).be.an.Array().and.match([`The room ${index2RoomName} does not match index ${index}`]);
      });
  });

  it('should return a response with partial error if a roomId doesn\'t correspond to the collection', function () {
    var
      collection2RoomName = '36a737bfc8da2f3c1673137a3b159d4a',
      requestObjectSubscribe1 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectSubscribe2 = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        index: index,
        collection: collection2,
        body: {}
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {rooms: [collection2RoomName]}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribe1, context)
      .then(() => kuzzle.hotelClerk.addSubscription(requestObjectSubscribe2, context))
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then((response) => {
        should(response.acknowledge).be.true();
        should(response.partialErrors.length).be.exactly(1);
        should(response.partialErrors).be.an.Array().and.match([`The room ${collection2RoomName} does not match collection ${collection1}`]);
      });
  });

  it('should return a response with partial error if a roomId doesn\'t exist', function () {
    var
      badRoomName = 'badRoomId',
      requestObjectSubscribe = new RequestObject({
        controller: 'subscribe',
        action: 'on',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {}
      }),
      requestObjectRemove = new RequestObject({
        controller: 'admin',
        action: 'removeRooms',
        requestId: roomName,
        index: index,
        collection: collection1,
        body: {rooms: [badRoomName]}
      });

    return kuzzle.hotelClerk.addSubscription(requestObjectSubscribe, context)
      .then(() => kuzzle.hotelClerk.removeRooms(requestObjectRemove))
      .then(response => {
        should(response.acknowledge).be.true();
        should(response.partialErrors.length).be.exactly(1);
        should(response.partialErrors).be.an.Array().and.match(['No room with id ' + badRoomName]);
      });
  });
});
<|endoftext|>


<commit_before>module.exports = {};

function calculateMove(game_state) {
  try {

    if(gameDecision.wantToBet()) {
      return gameDecision.getBetAmount();
    } else if(gameDecision.canWeKeepCards()) {
      // keep the cards if we can check
      // TODO: return current bet!!!
      return gameDecision.getCheckAmount();
    } else {

      //FOLD THE CARDS;
      return 0;
    }

    var bet = 110;
    var me = game_state["players"][game_state["in_action"]];
    var cards = me["hole_cards"];
    var first = cards[0];
    var second = cards[1];

    bet = get_minimum_raise(game_state) + bet;

    if(isNaN(parseInt(bet))){
      bet = 1100;
    }
    console.log("DO BET: "+bet);
    return bet;
  } catch(e) {
    console.log('caught horrible exception; folding!');
    return 0;
  }
}; module.exports.calculateMove = calculateMove;

function get_minimum_raise(game_state){
  return parseInt(game_state["current_buy_in"] - game_state["players"][game_state["in_action"]][game_state["bet"]] + game_state["minimum_raise"]);
}
<commit_msg>Include error message when logging caught exception<commit_after>module.exports = {};

function calculateMove(game_state) {
  try {

    if(gameDecision.wantToBet()) {
      return gameDecision.getBetAmount();
    } else if(gameDecision.canWeKeepCards()) {
      // keep the cards if we can check
      // TODO: return current bet!!!
      return gameDecision.getCheckAmount();
    } else {

      //FOLD THE CARDS;
      return 0;
    }

    var bet = 110;
    var me = game_state["players"][game_state["in_action"]];
    var cards = me["hole_cards"];
    var first = cards[0];
    var second = cards[1];

    bet = get_minimum_raise(game_state) + bet;

    if(isNaN(parseInt(bet))){
      bet = 1100;
    }
    console.log("DO BET: "+bet);
    return bet;
  } catch(e) {
    console.log('caught horrible exception:', e, 'folding!');
    return 0;
  }
}; module.exports.calculateMove = calculateMove;

function get_minimum_raise(game_state){
  return parseInt(game_state["current_buy_in"] - game_state["players"][game_state["in_action"]][game_state["bet"]] + game_state["minimum_raise"]);
}
<|endoftext|>


<commit_before>var expect = require("chai").expect;
var Unmarshaller = require("../../../lib/bindings/http/unmarshaller_0_3.js");
var Cloudevent = require("../../../index.js");
var v03 = require("../../../v03/index.js");

const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123";
const now = new Date();
const schemaurl = "http://cloudevents.io/schema.json";
const subject = "subject.ext";
const ceContentType = "application/json";

const data = {
  foo: "bar"
};

describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
  it("Throw error when payload is null", () => {
    // setup
    var payload = null;
    var un = new Unmarshaller();

    // act and assert
    return un.unmarshall(payload)
      .then(() => { throw new Error("failed"); })
      .catch((err) =>
        expect(err.message).to.equal("payload is null or undefined"));
  });

  it("Throw error when headers is null", () => {
    // setup
    var payload = {};
    var headers = null;
    var un = new Unmarshaller();

    // act and assert
    return un.unmarshall(payload, headers)
      .then(() => { throw new Error("failed"); })
      .catch((err) =>
        expect(err.message).to.equal("headers is null or undefined"));
  });

  it("Throw error when there is no content-type header", () => {
    // setup
    var payload = {};
    var headers = {};
    var un = new Unmarshaller();

    // act and assert
    un.unmarshall(payload, headers)
      .then(() => { throw new Error("failed"); })
      .catch((err) =>
        expect(err.message).to.equal("content-type header not found"));
  });

  it("Throw error when content-type is not allowed", () => {
    // setup
    var payload = {};
    var headers = {
      "content-type": "text/xml"
    };
    var un = new Unmarshaller();

    // act and assert
    un.unmarshall(payload, headers)
      .then(() => { throw new Error("failed"); })
      .catch((err) =>
        expect(err.message).to.equal("content type not allowed"));
  });

  describe("Structured", () => {
    it("Throw error when has not allowed mime", () => {
      // setup
      var payload = {};
      var headers = {
        "content-type": "application/cloudevents+zip"
      };
      var un = new Unmarshaller();

      // act and assert
      un.unmarshall(payload, headers)
        .then(() => { throw new Error("failed"); })
        .catch((err) =>
          expect(err.message).to.equal("structured+type not allowed"));
    });

    it("Throw error when the event does not follow the spec 0.3", () => {
      // setup
      var payload =
        new v03.CloudEvent(v03.Spec)
          .type(type)
          .source(source)
          .dataContentType(ceContentType)
          .time(now)
          .schemaurl(schemaurl)
          .data(data)
          .toString();

      var headers = {
        "content-type": "application/cloudevents+json"
      };

      var un = new Unmarshaller();

      // act and assert
      un.unmarshall(payload, headers)
        .then(() => { throw new Error("failed"); })
        .catch((err) =>
          expect(err.message).to.equal("invalid payload"));
    });

    it("Should accept event that follow the spec 0.3", () => {
      // setup
      var payload =
        new Cloudevent(v03.Spec)
          .type(type)
          .source(source)
          .dataContentType(ceContentType)
          .time(now)
          .schemaurl(schemaurl)
          .subject(subject)
          .data(data)
          .toString();

      var headers = {
        "content-type": "application/cloudevents+json"
      };

      var un = new Unmarshaller();

      // act and assert
      return un.unmarshall(payload, headers)
        .then((actual) =>
          expect(actual).to.be.an("object"))
        .catch((err) => {
          console.error(err);
          throw err;
        });
    });

    it("Should parse 'data' stringfied json to json object", () => {
      // setup
      var payload =
        new Cloudevent(v03.Spec)
          .type(type)
          .source(source)
          .dataContentType(ceContentType)
          .time(now)
          .schemaurl(schemaurl)
          .subject(subject)
          .data(JSON.stringify(data))
          .toString();

      var headers = {
        "content-type": "application/cloudevents+json"
      };

      var un = new Unmarshaller();

      // act and assert
      return un.unmarshall(payload, headers)
        .then((actual) => {
          expect(actual.getData()).to.deep.equal(data);
        })
        .catch((err) => {
          console.error(err);
          throw err;
        });
    });
  });

  describe("Binary", () => {
    it("Throw error when has not allowed mime", () => {
      // setup
      var payload = {
        data: "dataString"
      };
      var attributes = {
        "ce-type": "type",
        "ce-specversion": "0.3",
        "ce-source": "source",
        "ce-id": "id",
        "ce-time": "2019-06-16T11:42:00Z",
        "ce-schemaurl": "http://schema.registry/v1",
        "Content-Type": "text/html"
      };

      var un = new Unmarshaller();

      // act and assert
      un.unmarshall(payload, attributes)
        .then(() => { throw new Error("failed"); })
        .catch((err) =>
          expect(err.message).to.equal("content type not allowed"));
    });

    it("Throw error when the event does not follow the spec 0.3", () => {
      // setup
      var payload = {
        data: "dataString"
      };
      var attributes = {
        "ce-type": "type",
        "CE-CloudEventsVersion": "0.1",
        "ce-source": "source",
        "ce-id": "id",
        "ce-time": "2019-06-16T11:42:00Z",
        "ce-schemaurl": "http://schema.registry/v1",
        "Content-Type": "application/json"
      };

      var un = new Unmarshaller();

      // act and assert
      un.unmarshall(payload, attributes)
        .then(() => { throw new Error("failed"); })
        .catch((err) =>
          expect(err.message).to.not.empty);
    });

    it("No error when all attributes are in place", () => {
      // setup
      var payload = {
        data: "dataString"
      };
      var attributes = {
        "ce-type": "type",
        "ce-specversion": "0.3",
        "ce-source": "source",
        "ce-id": "id",
        "ce-time": "2019-06-16T11:42:00Z",
        "ce-schemaurl": "http://schema.registry/v1",
        "Content-Type": "application/json"
      };

      var un = new Unmarshaller();

      // act and assert
      un.unmarshall(payload, attributes)
        .then((actual) => expect(actual).to.be.an("object"));
    });

    it("Throw error when 'ce-datacontentencoding' is not allowed", () => {
      // setup
      var payload = "eyJtdWNoIjoid293In0=";

      var attributes = {
        "ce-type": "type",
        "ce-specversion": "0.3",
        "ce-source": "source",
        "ce-id": "id",
        "ce-time": "2019-06-16T11:42:00Z",
        "ce-schemaurl": "http://schema.registry/v1",
        "Content-Type": "application/json",
        "ce-datacontentencoding": "binary"
      };

      var un = new Unmarshaller();

      // act and assert
      return un.unmarshall(payload, attributes)
        .then(() => { throw new Error("failed"); })
        .catch((err) => {
          expect(err.message).to.equal("unsupported datacontentencoding");
        });
    });

    it("No error when 'ce-datacontentencoding' is base64", () => {
      // setup
      var payload = "eyJtdWNoIjoid293In0=";
      const expected = {
        much: "wow"
      };

      var attributes = {
        "ce-type": "type",
        "ce-specversion": "0.3",
        "ce-source": "source",
        "ce-id": "id",
        "ce-time": "2019-06-16T11:42:00Z",
        "ce-schemaurl": "http://schema.registry/v1",
        "Content-Type": "application/json",
        "ce-datacontentencoding": "base64"
      };

      var un = new Unmarshaller();

      // act and assert
      return un.unmarshall(payload, attributes)
        .then((actual) => expect(actual.getData()).to.deep.equal(expected))
        .catch((err) => {
          console.error(err);
          throw err;
        });
    });
  });
});
<commit_msg>test: use header constants in unmarshaller tests (#60)<commit_after>var expect = require("chai").expect;
var Unmarshaller = require("../../../lib/bindings/http/unmarshaller_0_3.js");
var Cloudevent = require("../../../index.js");
var v03 = require("../../../v03/index.js");

const type = "com.github.pull.create";
const source = "urn:event:from:myapi/resourse/123";
const now = new Date();
const schemaurl = "http://cloudevents.io/schema.json";
const subject = "subject.ext";
const {
  BINARY_HEADERS_03,
  HEADER_CONTENT_TYPE
} = require("../../../lib/bindings/http/constants.js");

const ceContentType = "application/json";

const data = {
  foo: "bar"
};

describe("HTTP Transport Binding Unmarshaller for CloudEvents v0.3", () => {
  it("Throw error when payload is null", () => {
    // setup
    var payload = null;
    var un = new Unmarshaller();

    // act and assert
    return un.unmarshall(payload)
      .then(() => { throw new Error("failed"); })
      .catch((err) =>
        expect(err.message).to.equal("payload is null or undefined"));
  });

  it("Throw error when headers is null", () => {
    // setup
    var payload = {};
    var headers = null;
    var un = new Unmarshaller();

    // act and assert
    return un.unmarshall(payload, headers)
      .then(() => { throw new Error("failed"); })
      .catch((err) =>
        expect(err.message).to.equal("headers is null or undefined"));
  });

  it("Throw error when there is no content-type header", () => {
    // setup
    var payload = {};
    var headers = {};
    var un = new Unmarshaller();

    // act and assert
    un.unmarshall(payload, headers)
      .then(() => { throw new Error("failed"); })
      .catch((err) =>
        expect(err.message).to.equal("content-type header not found"));
  });

  it("Throw error when content-type is not allowed", () => {
    // setup
    var payload = {};
    var headers = {
      "content-type": "text/xml"
    };
    var un = new Unmarshaller();

    // act and assert
    un.unmarshall(payload, headers)
      .then(() => { throw new Error("failed"); })
      .catch((err) =>
        expect(err.message).to.equal("content type not allowed"));
  });

  describe("Structured", () => {
    it("Throw error when has not allowed mime", () => {
      // setup
      var payload = {};
      var headers = {
        "content-type": "application/cloudevents+zip"
      };
      var un = new Unmarshaller();

      // act and assert
      un.unmarshall(payload, headers)
        .then(() => { throw new Error("failed"); })
        .catch((err) =>
          expect(err.message).to.equal("structured+type not allowed"));
    });

    it("Throw error when the event does not follow the spec 0.3", () => {
      // setup
      var payload =
        new v03.CloudEvent(v03.Spec)
          .type(type)
          .source(source)
          .dataContentType(ceContentType)
          .time(now)
          .schemaurl(schemaurl)
          .data(data)
          .toString();

      var headers = {
        "content-type": "application/cloudevents+json"
      };

      var un = new Unmarshaller();

      // act and assert
      un.unmarshall(payload, headers)
        .then(() => { throw new Error("failed"); })
        .catch((err) =>
          expect(err.message).to.equal("invalid payload"));
    });

    it("Should accept event that follow the spec 0.3", () => {
      // setup
      var payload =
        new Cloudevent(v03.Spec)
          .type(type)
          .source(source)
          .dataContentType(ceContentType)
          .time(now)
          .schemaurl(schemaurl)
          .subject(subject)
          .data(data)
          .toString();

      var headers = {
        "content-type": "application/cloudevents+json"
      };

      var un = new Unmarshaller();

      // act and assert
      return un.unmarshall(payload, headers)
        .then((actual) =>
          expect(actual).to.be.an("object"))
        .catch((err) => {
          console.error(err);
          throw err;
        });
    });

    it("Should parse 'data' stringfied json to json object", () => {
      // setup
      var payload =
        new Cloudevent(v03.Spec)
          .type(type)
          .source(source)
          .dataContentType(ceContentType)
          .time(now)
          .schemaurl(schemaurl)
          .subject(subject)
          .data(JSON.stringify(data))
          .toString();

      var headers = {
        "content-type": "application/cloudevents+json"
      };

      var un = new Unmarshaller();

      // act and assert
      return un.unmarshall(payload, headers)
        .then((actual) => {
          expect(actual.getData()).to.deep.equal(data);
        })
        .catch((err) => {
          console.error(err);
          throw err;
        });
    });
  });

  describe("Binary", () => {
    it("Throw error when has not allowed mime", () => {
      // setup
      var payload = {
        data: "dataString"
      };
      var attributes = {
        [BINARY_HEADERS_03.TYPE]: "type",
        [BINARY_HEADERS_03.SPEC_VERSION]: "0.3",
        [BINARY_HEADERS_03.SOURCE]: "source",
        [BINARY_HEADERS_03.ID]: "id",
        [BINARY_HEADERS_03.TIME]: "2019-06-16T11:42:00Z",
        [BINARY_HEADERS_03.SCHEMA_URL]: "http://schema.registry/v1",
        [HEADER_CONTENT_TYPE]: "text/html"
      };

      var un = new Unmarshaller();

      // act and assert
      un.unmarshall(payload, attributes)
        .then(() => { throw new Error("failed"); })
        .catch((err) =>
          expect(err.message).to.equal("content type not allowed"));
    });

    it("Throw error when the event does not follow the spec 0.3", () => {
      // setup
      var payload = {
        data: "dataString"
      };
      var attributes = {
        [BINARY_HEADERS_03.TYPE]: "type",
        "CE-CloudEventsVersion": "0.1",
        [BINARY_HEADERS_03.SOURCE]: "source",
        [BINARY_HEADERS_03.ID]: "id",
        [BINARY_HEADERS_03.TIME]: "2019-06-16T11:42:00Z",
        [BINARY_HEADERS_03.SCHEMA_URL]: "http://schema.registry/v1",
        [HEADER_CONTENT_TYPE]: "application/json"
      };

      var un = new Unmarshaller();

      // act and assert
      un.unmarshall(payload, attributes)
        .then(() => { throw new Error("failed"); })
        .catch((err) =>
          expect(err.message).to.not.empty);
    });

    it("No error when all attributes are in place", () => {
      // setup
      var payload = {
        data: "dataString"
      };
      var attributes = {
        [BINARY_HEADERS_03.TYPE]: "type",
        [BINARY_HEADERS_03.SPEC_VERSION]: "0.3",
        [BINARY_HEADERS_03.SOURCE]: "source",
        [BINARY_HEADERS_03.ID]: "id",
        [BINARY_HEADERS_03.TIME]: "2019-06-16T11:42:00Z",
        [BINARY_HEADERS_03.SCHEMA_URL]: "http://schema.registry/v1",
        [HEADER_CONTENT_TYPE]: "application/json"
      };

      var un = new Unmarshaller();

      // act and assert
      un.unmarshall(payload, attributes)
        .then((actual) => expect(actual).to.be.an("object"));
    });

    it("Throw error when 'ce-datacontentencoding' is not allowed", () => {
      // setup
      var payload = "eyJtdWNoIjoid293In0=";

      var attributes = {
        [BINARY_HEADERS_03.TYPE]: "type",
        [BINARY_HEADERS_03.SPEC_VERSION]: "0.3",
        [BINARY_HEADERS_03.SOURCE]: "source",
        [BINARY_HEADERS_03.ID]: "id",
        [BINARY_HEADERS_03.TIME]: "2019-06-16T11:42:00Z",
        [BINARY_HEADERS_03.SCHEMA_URL]: "http://schema.registry/v1",
        [HEADER_CONTENT_TYPE]: "application/json",
        [BINARY_HEADERS_03.CONTENT_ENCONDING]: "binary"
      };

      var un = new Unmarshaller();

      // act and assert
      return un.unmarshall(payload, attributes)
        .then(() => { throw new Error("failed"); })
        .catch((err) => {
          expect(err.message).to.equal("unsupported datacontentencoding");
        });
    });

    it("No error when 'ce-datacontentencoding' is base64", () => {
      // setup
      var payload = "eyJtdWNoIjoid293In0=";
      const expected = {
        much: "wow"
      };

      var attributes = {
        [BINARY_HEADERS_03.TYPE]: "type",
        [BINARY_HEADERS_03.SPEC_VERSION]: "0.3",
        [BINARY_HEADERS_03.SOURCE]: "source",
        [BINARY_HEADERS_03.ID]: "id",
        [BINARY_HEADERS_03.TIME]: "2019-06-16T11:42:00Z",
        [BINARY_HEADERS_03.SCHEMA_URL]: "http://schema.registry/v1",
        [HEADER_CONTENT_TYPE]: "application/json",
        [BINARY_HEADERS_03.CONTENT_ENCONDING]: "base64"
      };

      var un = new Unmarshaller();

      // act and assert
      return un.unmarshall(payload, attributes)
        .then((actual) => expect(actual.getData()).to.deep.equal(expected))
        .catch((err) => {
          console.error(err);
          throw err;
        });
    });
  });
});
<|endoftext|>


<commit_before>import { Clipboard } from 'react-native';
import { narrowFromMessage } from '../utils/narrow';
import { getSingleMessage } from '../api';
import { isTopicMuted } from '../utils/message';
import muteTopicApi from '../api/muteTopic';
import unmuteTopicApi from '../api/unmuteTopic';
import unmuteStreamApi from '../api/unmuteStream';
import muteStreamApi from '../api/muteStream';

const narrowToConversation = ({ message, doNarrow }) => {
  doNarrow(narrowFromMessage(message), message.id);
};

const reply = ({ message, doNarrow }) => {
  doNarrow(narrowFromMessage(message), message.id);
};

const copyToClipboard = async ({ message, auth }) => {
  const rawMessage = await getSingleMessage(auth, message.id);
  Clipboard.setString(rawMessage);
};

const unmuteTopic = ({ auth, message }) => {
  unmuteTopicApi(auth, message.display_recipient, message.subject);
};

const muteTopic = ({ auth, message }) => {
  muteTopicApi(auth, message.display_recipient, message.subject);
};

const unmuteStream = ({ auth, message, subscriptions }) => {
  const sub = subscriptions.find(x => x.name === message.display_recipient);
  unmuteStreamApi(auth, sub.stream_id);
};

const muteStream = ({ auth, message, subscriptions }) => {
  const sub = subscriptions.find(x => x.name === message.display_recipient);
  muteStreamApi(auth, sub.stream_id);
};

const skip = () => false;

const actionSheetButtons = [
  { title: 'Narrow to conversation', onPress: narrowToConversation },
  { title: 'Reply', onPress: reply },
  { title: 'Copy to clipboard', onPress: copyToClipboard },
  // If skip then covered in constructActionButtons
  { title: 'Unmute topic', onPress: unmuteTopic, onlyIf: skip },
  { title: 'Mute topic', onPress: muteTopic, onlyIf: skip },
  { title: 'Mute stream', onPress: muteStream, onlyIf: skip },
  { title: 'Unmute stream', onPress: unmuteStream, onlyIf: skip },
  { title: 'Cancel', onPress: skip, onlyIf: skip },
];

export const constructActionButtons = ({ message, auth, narrow, subscriptions, mute }) => {
  const buttons = actionSheetButtons.filter(x =>
    !x.onlyIf || x.onlyIf({ message, auth, narrow })).map(x => x.title);

  // These are dependent conditions, hence better if we manage here rather than using onlyIf
  if (message.type === 'stream') {
    if (isTopicMuted(message, mute)) {
      buttons.push('Unmute topic');
    } else {
      buttons.push('Mute topic');
    }
    const sub = subscriptions.find(x => x.name === message.display_recipient);
    if (sub && !sub.in_home_view) {
      buttons.push('Unmute stream');
    } else {
      buttons.push('Mute stream');
    }
  }
  buttons.push('Cancel');
  return buttons;
};

export const executeActionSheetAction = ({ title, ...props }) => {
  actionSheetButtons.find(x => x.title === title).onPress(props);
};
<commit_msg>Removed Narrow to conversation<commit_after>import { Clipboard } from 'react-native';
import { narrowFromMessage } from '../utils/narrow';
import { getSingleMessage } from '../api';
import { isTopicMuted } from '../utils/message';
import muteTopicApi from '../api/muteTopic';
import unmuteTopicApi from '../api/unmuteTopic';
import unmuteStreamApi from '../api/unmuteStream';
import muteStreamApi from '../api/muteStream';

const reply = ({ message, doNarrow }) => {
  doNarrow(narrowFromMessage(message), message.id);
};

const copyToClipboard = async ({ message, auth }) => {
  const rawMessage = await getSingleMessage(auth, message.id);
  Clipboard.setString(rawMessage);
};

const unmuteTopic = ({ auth, message }) => {
  unmuteTopicApi(auth, message.display_recipient, message.subject);
};

const muteTopic = ({ auth, message }) => {
  muteTopicApi(auth, message.display_recipient, message.subject);
};

const unmuteStream = ({ auth, message, subscriptions }) => {
  const sub = subscriptions.find(x => x.name === message.display_recipient);
  unmuteStreamApi(auth, sub.stream_id);
};

const muteStream = ({ auth, message, subscriptions }) => {
  const sub = subscriptions.find(x => x.name === message.display_recipient);
  muteStreamApi(auth, sub.stream_id);
};

const skip = () => false;

const actionSheetButtons = [
  { title: 'Reply', onPress: reply },
  { title: 'Copy to clipboard', onPress: copyToClipboard },
  // If skip then covered in constructActionButtons
  { title: 'Unmute topic', onPress: unmuteTopic, onlyIf: skip },
  { title: 'Mute topic', onPress: muteTopic, onlyIf: skip },
  { title: 'Mute stream', onPress: muteStream, onlyIf: skip },
  { title: 'Unmute stream', onPress: unmuteStream, onlyIf: skip },
  { title: 'Cancel', onPress: skip, onlyIf: skip },
];

export const constructActionButtons = ({ message, auth, narrow, subscriptions, mute }) => {
  const buttons = actionSheetButtons.filter(x =>
    !x.onlyIf || x.onlyIf({ message, auth, narrow })).map(x => x.title);

  // These are dependent conditions, hence better if we manage here rather than using onlyIf
  if (message.type === 'stream') {
    if (isTopicMuted(message, mute)) {
      buttons.push('Unmute topic');
    } else {
      buttons.push('Mute topic');
    }
    const sub = subscriptions.find(x => x.name === message.display_recipient);
    if (sub && !sub.in_home_view) {
      buttons.push('Unmute stream');
    } else {
      buttons.push('Mute stream');
    }
  }
  buttons.push('Cancel');
  return buttons;
};

export const executeActionSheetAction = ({ title, ...props }) => {
  actionSheetButtons.find(x => x.title === title).onPress(props);
};
<|endoftext|>


<commit_before>//svg container
var svg = d3.select("body")
    .append("svg")
    .attr("viewBox", "0 0 500 100")
    .style("border", "1px solid black");;

//circles
var circles = svg
    .selectAll("circle")
    .data(data)
    .enter()
    .append("circle");
var circleAttr = circles
    .attr("cx", function(d, i) {
        var xpos = (i * 10 + 5) * 2;
        return xpos;
    })
    .attr("cy", 25)
    .attr("r", function(d) {
        return d;
    })
    .style("fill", "green");

//showing data
d3.select("body")
    .append("div")
    .text(function() {
        var d2show = "Data: ";
        for (var i = 0; i < data.length; i++) {
            d2show += data[i] + " ";
        }
        return d2show;
    });

///////////////Graph

var divDOM = d3.select("body").select("div");
var svgGraph = divDOM.append("svg");
var svgWidth = 2000;
var svgHeight = 1000;
svgGraph.attr("viewBox", "0 0 " + svgWidth + " " + svgHeight);
svgGraph.style("border", "1px solid black");
var x_axisOffset = 50;
var y_axisOffset = 50;
var noOfXMarkers = data.length;
var noOfYMarkers = 10;
var legendMarkerLength = 7;

//x-axis
var x_axis = svgGraph.append("g");
x_axis.attr("id", "x_axis");
x_axis.append("line")
    .attr("x1", x_axisOffset)
    .attr("y1", svgHeight - y_axisOffset)
    .attr("x2", svgWidth - x_axisOffset)
    .attr("y2", svgHeight - y_axisOffset)
    .style("stroke", "black").style("stroke-width", 1);
x_axis.append("polyline")
    .attr("points", function() {
        var pointx = svgWidth - x_axisOffset;
        var pointy = svgHeight - y_axisOffset;
        return (pointx - 7) + "," + (pointy - 7) + " " + pointx + "," + pointy + " " + (pointx - 7) + "," + (pointy + 7);
    })
    .attr("fill", "none")
    .style("stroke", "black").style("stroke-width", 1);
var x_axisLegend = x_axis.append("g");
for (var i = 1; i <= noOfXMarkers; i++) {
    var xcor = x_axisOffset + i * 0.9 * (svgWidth - 2 * x_axisOffset) / noOfXMarkers;
    x_axisLegend.append("line")
        .attr("x1", xcor)
        .attr("y1", svgHeight - y_axisOffset - legendMarkerLength)
        .attr("x2", xcor)
        .attr("y2", svgHeight - y_axisOffset + legendMarkerLength)
        .style("stroke", "black").style("stroke-width", 2);
    x_axisLegend.append("text")
        .text(i * data.length / noOfXMarkers)
        .attr("x", xcor)
        .attr("y", svgHeight - y_axisOffset + 30)
        .attr("font-family", "sans-serif")
        .attr("font-size", "25px")
        .attr("text-anchor", "middle")
        .attr("fill", "black");
}

//y-axis
var y_axis = svgGraph.append("g");
y_axis.attr("id", "y_axis");
y_axis.append("line")
    .attr("x1", x_axisOffset)
    .attr("y1", y_axisOffset)
    .attr("x2", x_axisOffset)
    .attr("y2", svgHeight - y_axisOffset)
    .style("stroke", "black").style("stroke-width", 1);
y_axis.append("polyline")
    .attr("points", function() {
        var pointx = x_axisOffset;
        var pointy = y_axisOffset;
        return (pointx - 7) + "," + (pointy + 7) + " " + pointx + "," + pointy + " " + (pointx + 7) + "," + (pointy + 7);
    })
    .attr("fill", "none")
    .style("stroke", "black").style("stroke-width", 1);
var y_axisLegend = y_axis.append("g");
for (var i = 1; i <= noOfXMarkers; i++) {
    var ycor = svgHeight - y_axisOffset - i * 0.9 * (svgHeight - 2 * y_axisOffset) / noOfYMarkers;
    y_axisLegend.append("line")
        .attr("x1", x_axisOffset - legendMarkerLength)
        .attr("y1", ycor)
        .attr("x2", x_axisOffset + legendMarkerLength)
        .attr("y2", ycor)
        .style("stroke", "black").style("stroke-width", 2);
    y_axisLegend.append("text")
        .text(i * data.length / noOfYMarkers)
        .attr("x", x_axisOffset - 30)
        .attr("y", ycor)
        .attr("font-family", "sans-serif")
        .attr("font-size", "25px")
        .attr("text-anchor", "middle")
        .attr("fill", "black");
}

//Graph Points
var plotArea = svgGraph.append("g");
plotArea.attr("id", "plotArea");

//Graph Functions

//Plot a single point
function plotPoint(x, y, pointSize) {
    if (pointSize === undefined) pointSize = 3;
    var point = plotArea.append("circle");
    point.attr("cx", x + x_axisOffset);
    point.attr("cy", svgHeight - y - y_axisOffset);
    point.attr("r", pointSize);
    point.attr("fill", "black");
}

//plotting points from data
function plotDataPoints() {
    var maxY = data[0];
    for (var i = 0; i < data.length; i++) {
        if (data[i] > maxY) maxY = data[i];
    }
    var scaleX = 0.9 * (svgWidth - 2 * x_axisOffset) / data.length;
    var scaleY = 0.9 * (svgHeight - 2 * y_axisOffset) / maxY;
    for (var i = 0; i < data.length; i++) {
        plotPoint(i * scaleX, data[i] * scaleY);
    }
}
plotDataPoints();
<commit_msg>Y-axis numbers positioned correctly<commit_after>//svg container
var svg = d3.select("body")
    .append("svg")
    .attr("viewBox", "0 0 500 100")
    .style("border", "1px solid black");;

//circles
var circles = svg
    .selectAll("circle")
    .data(data)
    .enter()
    .append("circle");
var circleAttr = circles
    .attr("cx", function(d, i) {
        var xpos = (i * 10 + 5) * 2;
        return xpos;
    })
    .attr("cy", 25)
    .attr("r", function(d) {
        return d;
    })
    .style("fill", "green");

//showing data
d3.select("body")
    .append("div")
    .text(function() {
        var d2show = "Data: ";
        for (var i = 0; i < data.length; i++) {
            d2show += data[i] + " ";
        }
        return d2show;
    });

///////////////Graph

var divDOM = d3.select("body").select("div");
var svgGraph = divDOM.append("svg");
var svgWidth = 2000;
var svgHeight = 1000;
svgGraph.attr("viewBox", "0 0 " + svgWidth + " " + svgHeight);
svgGraph.style("border", "1px solid black");
var x_axisOffset = 70;
var y_axisOffset = 50;
var noOfXMarkers = data.length;
var noOfYMarkers = 10;
var legendMarkerLength = 7;

//x-axis
var x_axis = svgGraph.append("g");
x_axis.attr("id", "x_axis");
x_axis.append("line")
    .attr("x1", x_axisOffset)
    .attr("y1", svgHeight - y_axisOffset)
    .attr("x2", svgWidth - x_axisOffset)
    .attr("y2", svgHeight - y_axisOffset)
    .style("stroke", "black").style("stroke-width", 1);
x_axis.append("polyline")
    .attr("points", function() {
        var pointx = svgWidth - x_axisOffset;
        var pointy = svgHeight - y_axisOffset;
        return (pointx - 7) + "," + (pointy - 7) + " " + pointx + "," + pointy + " " + (pointx - 7) + "," + (pointy + 7);
    })
    .attr("fill", "none")
    .style("stroke", "black").style("stroke-width", 1);
var x_axisLegend = x_axis.append("g");
for (var i = 1; i <= noOfXMarkers; i++) {
    var xcor = x_axisOffset + i * 0.9 * (svgWidth - 2 * x_axisOffset) / noOfXMarkers;
    x_axisLegend.append("line")
        .attr("x1", xcor)
        .attr("y1", svgHeight - y_axisOffset - legendMarkerLength)
        .attr("x2", xcor)
        .attr("y2", svgHeight - y_axisOffset + legendMarkerLength)
        .style("stroke", "black").style("stroke-width", 2);
    x_axisLegend.append("text")
        .text(i * data.length / noOfXMarkers)
        .attr("x", xcor)
        .attr("y", svgHeight - y_axisOffset + 30)
        .attr("font-family", "sans-serif")
        .attr("font-size", "25px")
        .attr("text-anchor", "middle")
        .attr("fill", "black");
}

//y-axis
var y_axis = svgGraph.append("g");
y_axis.attr("id", "y_axis");
y_axis.append("line")
    .attr("x1", x_axisOffset)
    .attr("y1", y_axisOffset)
    .attr("x2", x_axisOffset)
    .attr("y2", svgHeight - y_axisOffset)
    .style("stroke", "black").style("stroke-width", 1);
y_axis.append("polyline")
    .attr("points", function() {
        var pointx = x_axisOffset;
        var pointy = y_axisOffset;
        return (pointx - 7) + "," + (pointy + 7) + " " + pointx + "," + pointy + " " + (pointx + 7) + "," + (pointy + 7);
    })
    .attr("fill", "none")
    .style("stroke", "black").style("stroke-width", 1);
var y_axisLegend = y_axis.append("g");
for (var i = 1; i <= noOfXMarkers; i++) {
    var ycor = svgHeight - y_axisOffset - i * 0.9 * (svgHeight - 2 * y_axisOffset) / noOfYMarkers;
    y_axisLegend.append("line")
        .attr("x1", x_axisOffset - legendMarkerLength)
        .attr("y1", ycor)
        .attr("x2", x_axisOffset + legendMarkerLength)
        .attr("y2", ycor)
        .style("stroke", "black").style("stroke-width", 2);
    y_axisLegend.append("text")
        .text(i * data.length / noOfYMarkers)
        .attr("x", x_axisOffset - 40)
        .attr("y", ycor + 10)
        .attr("font-family", "sans-serif")
        .attr("font-size", "25px")
        .attr("text-anchor", "middle")
        .attr("fill", "black");
}

//Graph Points
var plotArea = svgGraph.append("g");
plotArea.attr("id", "plotArea");

//Graph Functions

//Plot a single point
function plotPoint(x, y, pointSize) {
    if (pointSize === undefined) pointSize = 3;
    var point = plotArea.append("circle");
    point.attr("cx", x + x_axisOffset);
    point.attr("cy", svgHeight - y - y_axisOffset);
    point.attr("r", pointSize);
    point.attr("fill", "black");
}

//plotting points from data
function plotDataPoints() {
    var maxY = data[0];
    for (var i = 0; i < data.length; i++) {
        if (data[i] > maxY) maxY = data[i];
    }
    var scaleX = 0.9 * (svgWidth - 2 * x_axisOffset) / data.length;
    var scaleY = 0.9 * (svgHeight - 2 * y_axisOffset) / maxY;
    for (var i = 0; i < data.length; i++) {
        plotPoint(i * scaleX, data[i] * scaleY);
    }
}
plotDataPoints();
<|endoftext|>


<commit_before>/*eslint-env node, mocha */
/*global expect */
/*eslint no-console: 0*/
'use strict';

import React from 'react';
import { shallow } from 'enzyme';

// Uncomment the following lines to use the react test utilities
// import TestUtils from 'react-addons-test-utils';
import IframeLockerComponent from 'components//IframeLockerComponent.js';

import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

describe.only('IframeLockerComponent', () => {
  let component;

  beforeEach(() => {
    component = shallow(
      <IframeLockerComponent
        next={() => {}}
        prev={() => {}}
      />
    );
  });

  it('should have its component name as default className', () => {
    expect(component.prop('className')).to.equal('iframelocker-component');
  });

  it('should display a snackbar on touch tap', () => {
    expect(component.state('open')).to.be.false;
    component.find('div').simulate('touchTap');
    expect(component.state('open')).to.be.ture;
  });

  it('should go to the previous screen after swipe left', () => {

  });

  it('should go to the next screen after swipe right', () => {

  });
});
<commit_msg>Adds specs for IframeLockerComponent<commit_after>/*eslint-env node, mocha */
/*global expect */
/*eslint no-console: 0*/
'use strict';

import React from 'react';
import { shallow } from 'enzyme';

// Uncomment the following lines to use the react test utilities
// import TestUtils from 'react-addons-test-utils';
import IframeLockerComponent from 'components//IframeLockerComponent.js';

import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();

describe('IframeLockerComponent', () => {
  let component;
  const next = sinon.spy();
  const prev = sinon.spy();

  beforeEach(() => {
    component = shallow(
      <IframeLockerComponent
        next={next}
        prev={prev}
      />
    );
  });

  it('should have its component name as default className', () => {
    expect(component.prop('className')).to.equal('iframelocker-component');
  });

  it('should display a snackbar on touch tap', () => {
    expect(component.state('open')).to.be.false;
    component.find('div').simulate('touchTap');
    expect(component.state('open')).to.be.ture;
  });

  it.skip('should go to the previous screen after swipe left', () => {
    expect(prev).calledOnce;
  });

  it.skip('should go to the next screen after swipe right', () => {
    expect(next).calledOnce;
  });
});
<|endoftext|>


<commit_before>define(function() {

  'use strict';

  function WriteFileHeaderView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
  }
  WriteFileHeaderView.prototype = {
    get hasValidSignature() {
      return this.signature === 0xBE31 || this.signature === 0xBE32;
    },
    get isWordFile() {
      return this.pageCount === 0;
    },
    get containsOLE() {
      return this.signature === 0xBE32;
    },

    get signature() {
      return this.dv.getUint16(0, true);
    },
    // 0x02: must be 0x0000
    // 0x04: must be 0x00AB
    // reserved uint16 x4

    // bytes of actual text plus 128, the bytes in one sector
    get fcMac() {
      return this.dv.getUint32(14, true);
    },
    get characterInfoFirstPageNumber() {
      return (this.dv.getUint32(14, true) + 0x7f) >>> 7;
    },
    get paragraphInfoFirstPageNumber() {
      return this.dv.getUint16(18, true);
    },
    get paragraphInfoLastPageNumber() {
      return this.dv.getUint16(20, true) - 1;
    },
    get footnoteTablePageNumber() {
      var page = this.dv.getUint16(20, true);
      return (page === this.dv.getInt16(22, true)) ? -1 : page;
    },
    get sectionPropertyPageNumber() {
      var page = this.dv.getUint16(22, true);
      return (page === this.dv.getUint16(24, true)) ? -1 : page;
    },
    get sectionTablePageNumber() {
      var page = this.dv.getUint16(24, true);
      return (page === this.dv.getUint16(26, true)) ? -1 : page;
    },
    get pageTablePageNumber() {
      var page = this.dv.getUint16(26, true);
      return (page === this.dv.getUint16(28, true)) ? -1 : page;
    },
    get fontNameTablePageNumber() {
      var page = this.dv.getInt16(28, true);
      return (page === this.dv.getUint16(96, true)) ? -1 : page;
    },
    // 66 bytes reserved (Word compatibility)
    get pageCount() {
      return this.dv.getInt16(96, true);
    },
    // reserved uint16 x15
  };
  HeaderView.byteLength = 128;

  return {
    FileHeaderView: WriteFileHeaderView,
  };

});
<commit_msg>Simplify header view interface<commit_after>define(function() {

  'use strict';

  var PAGE_BYTES = 128;

  function WriteFileHeaderView(buffer, byteOffset, byteLength) {
    this.dv = new DataView(buffer, byteOffset, byteLength);
  }
  WriteFileHeaderView.prototype = {
    get hasValidSignature() {
      return this.signature === 0xBE31 || this.signature === 0xBE32;
    },
    get isWordFile() {
      return this.pageCount === 0;
    },
    get containsOLE() {
      return this.signature === 0xBE32;
    },

    get signature() {
      return this.dv.getUint16(0, true);
    },
    // 0x02: must be 0x0000
    // 0x04: must be 0x00AB
    // reserved uint16 x4

    get textOffset() {
      return PAGE_BYTES;
    },
    get textLength() {
      return this.dv.getUint32(14, true);
    },
    get characterInfoOffset() {
      return this.textOffset + PAGE_BYTES * Math.ceil(this.textByteLength / PAGE_BYTES);
    },
    get characterInfoBlockLength() {
      return this.paragraphInfoOffset - this.characterInfoOffset;
    },
    get paragraphInfoOffset() {
      return PAGE_BYTES * this.dv.getUint16(18, true);
    },
    get paragraphInfoBlockLength() {
      return PAGE_BYTES * (this.dv.getUint16(20, true) - this.dv.getUint16(18, true));
    },
    get footnoteTableOffset() {
      return PAGE_BYTES * this.dv.getUint16(20, true);
    },
    get footnoteTableBlockLength() {
      return PAGE_BYTES * (this.dv.getUint16(22, true) - this.dv.getUint16(20, true));
    },
    get sectionPropertyOffset() {
      return PAGE_BYTES * this.dv.getUint16(22, true);
    },
    get sectionTableBlockLength() {
      return PAGE_BYTES * (this.dv.getUint16(24, true) - this.dv.getUint16(22, true));
    },
    get pageTableOffset() {
      return PAGE_BYTES * this.dv.getUint16(26, true);
    },
    get pageTableBlockLength() {
      return PAGE_BYTES * (this.dv.getUint16(28, true) - this.dv.getUint16(26, true));
    },
    get fontNameTableOffset() {
      return PAGE_BYTES * this.dv.getInt16(28, true);
    },
    get fontNameTableBlockLength() {
      return PAGE_BYTES * (this.dv.getInt16(96, true) - this.dv.getInt16(28, true));
    },
    // 66 bytes reserved (Word compatibility)
    get totalBlockLength() {
      return PAGE_BYTES * this.dv.getInt16(96, true);
    },
    // reserved uint16 x15
  };
  HeaderView.byteLength = PAGE_BYTES;

  return {
    FileHeaderView: WriteFileHeaderView,
  };

});
<|endoftext|>