<commit_before>/*
    Copyright (c) 2016 eyeOS

    This file is part of Open365.

    Open365 is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';
define([
	'desktop/desktopInitializerService'
], function(DesktopInitializer) {
	suite('Service: desktopInitializer', function () {
		var sut;
		var desktopAuthService,
			desktopBusService,
			suspensionDetector;
		var settings;

		setup(function () {
			settings = {
				ENVIRONMENT: 'release'
			};
			desktopAuthService = {
				checkCard: function () {},
				forceCheckCard: sinon.stub()
			};

			desktopBusService = {
				connectToBus: function () {
				}
			};

			suspensionDetector = {
				start: sinon.stub(),
				addOnAwakeAction: sinon.stub()
			};

			sut = new DesktopInitializer(desktopAuthService, desktopBusService, suspensionDetector);
		});

		function expect_desktopBusService_connectToBus_called (sinon, times) {
			sinon.mock(desktopBusService)
				.expects('connectToBus')
				.exactly(times)
				.withExactArgs();
		}

		suite('#setAuthClientLoaded', function () {

			setup(function () {
			});

			function exercise () {
				sut.setAuthClientLoaded(settings);
			}

			test('calls desktopAuthService.checkCard', sinon.test(function () {
				this.mock(desktopAuthService)
					.expects('checkCard')
					.once()
					.withExactArgs(sinon.match.func);
				exercise();
			}));

			suite('when checkCard callback is executed', function () {

				test('should call desktopBusService.connectToBus', sinon.test(function () {
					var checkCardStub = sinon.stub(desktopAuthService, 'checkCard');
					expect_desktopBusService_connectToBus_called(this, 1);
					checkCardStub.callsArgWith(0);
					exercise();
				}));

			});
		});

		suite("#handleComputerSuspension", function () {
			function exercice () {
				sut.handleComputerSuspension();
			}

			test('forces a checkCard on awake', function () {
				suspensionDetector.addOnAwakeAction.callsArg(0);
				exercice();
				sinon.assert.calledOnce(desktopAuthService.forceCheckCard);
			});
		});
	});

});
<commit_msg>Fix tests<commit_after>/*
    Copyright (c) 2016 eyeOS

    This file is part of Open365.

    Open365 is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';
define([
	'desktop/desktopInitializerService'
], function(DesktopInitializer) {
	suite('Service: desktopInitializer', function () {
		var sut;
		var desktopAuthService,
			desktopBusService,
			suspensionDetector;
		var settings;

		setup(function () {
			settings = {
				ENVIRONMENT: 'release'
			};
			desktopAuthService = {
				checkCard: function () {},
				forceCheckCard: sinon.stub()
			};

			desktopBusService = {
				connectToBus: function () {
				}
			};

			suspensionDetector = {
				start: sinon.stub(),
				addOnAwakeAction: sinon.stub()
			};

			sut = new DesktopInitializer(desktopAuthService, desktopBusService, suspensionDetector);
		});

		function expect_desktopBusService_connectToBus_called (sinon, times) {
			sinon.mock(desktopBusService)
				.expects('connectToBus')
				.exactly(times)
				.withExactArgs();
		}

		suite('#setAuthClientLoaded', function () {

			setup(function () {
			});

			function exercise () {
				sut.setAuthClientLoaded(settings);
			}

			test('calls desktopAuthService.checkCard', sinon.test(function () {
				this.mock(desktopAuthService)
					.expects('checkCard')
					.once()
					.withExactArgs(sinon.match.func);
				exercise();
			}));

			suite('when checkCard callback is executed', function () {

				test('should call desktopBusService.connectToBus', sinon.test(function () {
					var checkCardStub = sinon.stub(desktopAuthService, 'checkCard');
					expect_desktopBusService_connectToBus_called(this, 1);
					checkCardStub.callsArgWith(0);
					exercise();
				}));

			});
		});

		suite("#handleComputerSuspension", function () {
			function exercice () {
				sut.handleComputerSuspension();
			}

			test('forces a checkCard on awake', function () {
				suspensionDetector.addOnAwakeAction.callsArg(0);
				var stub = sinon.stub(desktopAuthService, "checkCard");
				exercice();
				sinon.assert.calledOnce(stub);
			});
		});
	});

});
<|endoftext|>


<commit_before>/* @flow */

const {
  after,
  afterEach,
  before,
  beforeEach,
  suite,
  test
} = require('mocha')
const should = require('should')

const metadata = require('../../core/metadata')

const Builders = require('../support/builders')
const configHelpers = require('../support/helpers/config')
const cozyHelpers = require('../support/helpers/cozy')
const pouchHelpers = require('../support/helpers/pouch')
const { IntegrationTestHelpers } = require('../support/helpers/integration')

suite('Platform incompatibilities', () => {
  let builders, cozy, helpers

  before(configHelpers.createConfig)
  before(configHelpers.registerClient)
  beforeEach(pouchHelpers.createDatabase)
  beforeEach(cozyHelpers.deleteAll)

  afterEach(() => helpers.local.clean())
  afterEach(pouchHelpers.cleanDatabase)
  after(configHelpers.cleanConfig)

  beforeEach(async function () {
    cozy = cozyHelpers.cozy
    builders = new Builders(cozy, this.pouch)
    helpers = new IntegrationTestHelpers(this.config, this.pouch, cozy)

    await helpers.local.setupTrash()
    await helpers.remote.ignorePreviousChanges()
  })

  if (process.platform !== 'win32' && process.platform !== 'darwin') {
    test.skip(`is not tested on ${process.platform}`, () => {})
  } else {
    test('add incompatible dir and file', async () => {
      await builders.remote.dir().named('di:r').create()
      await builders.remote.file().named('fi:le').create()
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).be.empty()
    })
    test('add incompatible dir with two colons', async () => {
      await builders.remote.dir().named('d:i:r').create()
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).be.empty()
    })
    test('add compatible dir with some incompatible content', async () => {
      await helpers.remote.createTree([
        'dir/',
        'dir/file',
        'dir/fi:le',
        'dir/sub:dir/',
        'dir/sub:dir/file',
        'dir/subdir/',
        'dir/subdir/file'
      ])
      await helpers.pullAndSyncAll()

      should(await helpers.local.tree()).deepEqual([
        'dir/',
        'dir/file',
        'dir/subdir/',
        'dir/subdir/file'
      ])
    })
    test('rename incompatible -> incompatible', async () => {
      await helpers.remote.createTree(['d:ir/', 'f:ile'])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesByPath('/d:ir', {name: 'di:r'})
      await cozy.files.updateAttributesByPath('/f:ile', {name: 'fi:le'})
      await helpers.pullAndSyncAll()

      should(await helpers.local.tree()).be.empty()
    })
    test('trash & restore incompatible', async () => {
      const docs = await helpers.remote.createTree(['d:ir/', 'f:ile'])
      await helpers.pullAndSyncAll()

      await cozy.files.trashById(docs['d:ir/']._id)
      await cozy.files.trashById(docs['f:ile']._id)
      await helpers.pullAndSyncAll()

      should(await helpers.local.tree()).be.empty()

      await cozy.files.restoreById(docs['d:ir/']._id)
      await cozy.files.restoreById(docs['f:ile']._id)
      await helpers.pullAndSyncAll()

      should(await helpers.local.tree()).be.empty()
    })

    test('destroy & recreate incompatible', async () => {
      const docs = await helpers.remote.createTree(['d:ir/', 'f:ile'])
      await helpers.pullAndSyncAll()

      await cozy.files.trashById(docs['d:ir/']._id)
      await cozy.files.trashById(docs['f:ile']._id)
      await cozy.files.destroyById(docs['d:ir/']._id)
      await cozy.files.destroyById(docs['f:ile']._id)
      await helpers.pullAndSyncAll()

      should(await helpers.local.tree()).be.empty()

      await helpers.remote.createTree(['d:ir/', 'f:ile'])
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).be.empty()
    })

    test('make compatible bottom-up', async () => {
      const docs = await helpers.remote.createTree([
        'd:ir/',
        'd:ir/sub:dir/',
        'd:ir/sub:dir/f:ile',
        'd:ir/sub:dir/subsubdir/'
      ])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesById(docs['d:ir/sub:dir/f:ile']._id, {name: 'file'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).be.empty()

      await cozy.files.updateAttributesById(docs['d:ir/']._id, {name: 'dir'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        'dir/'
      ])

      await cozy.files.updateAttributesById(docs['d:ir/sub:dir/']._id, {name: 'subdir'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        'dir/',
        'dir/subdir/',
        'dir/subdir/file',
        'dir/subdir/subsubdir/'
      ])
    })

    test('rename dir compatible -> incompatible', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/subdir/',
        'dir/subdir/file'
      ])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesById(docs['dir/']._id, {name: 'dir:'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        '/Trash/dir/',
        '/Trash/dir/subdir/',
        '/Trash/dir/subdir/file'
      ])
    })

    test('rename dir compatible -> incompatible with already incompatible content', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/sub:dir/',
        'dir/sub:dir/file'
      ])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesById(docs['dir/']._id, {name: 'dir:'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        '/Trash/dir/'
      ])
    })

    test('rename file compatible -> incompatible', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/file'
      ])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesById(docs['dir/file']._id, {name: 'fi:le'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        '/Trash/file',
        'dir/'
      ])
    })

    test('rename dir compatible -> compatible with incompatible content', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/fi:le',
        'dir/sub:dir/'
      ])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesById(docs['dir/']._id, {name: 'dir2'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        'dir2/'
      ])
    })

    test('move local dir with incompatible metadata & remote content', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/sub:dir/',
        'dir/sub:dir/file'
      ])
      await helpers.pullAndSyncAll()

      // Simulate local move
      const dir = await helpers._pouch.byRemoteIdAsync(docs['dir/']._id)
      const stats = {mtime: new Date(), ctime: new Date(), ino: dir.ino}
      // $FlowFixMe
      const dir2 = metadata.buildDir('dir2', stats)
      await helpers.prep.moveFolderAsync('local', dir2, dir)
      await helpers.syncAll()

      should(await helpers.remote.tree()).deepEqual([
        '.cozy_trash/',
        'dir2/',
        'dir2/sub:dir/',
        'dir2/sub:dir/file'
      ])
    })

    test('rename dir compatible -> incompatible -> compatible with compatible content', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/file'
      ])
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        'dir/',
        'dir/file'
      ])

      await cozy.files.updateAttributesById(docs['dir/']._id, {name: 'd:ir'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        '/Trash/dir/',
        '/Trash/dir/file'
      ])

      await cozy.files.updateAttributesById(docs['dir/']._id, {name: 'dir'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        // XXX: We don't restore from OS trash for now. Hence the copy.
        '/Trash/dir/',
        '/Trash/dir/file',
        'dir/',
        'dir/file'
      ])
    })
  }
})
<commit_msg>test/integration: Assert incompatible metadata is removed on destroy<commit_after>/* @flow */

const {
  after,
  afterEach,
  before,
  beforeEach,
  suite,
  test
} = require('mocha')
const should = require('should')

const metadata = require('../../core/metadata')

const Builders = require('../support/builders')
const configHelpers = require('../support/helpers/config')
const cozyHelpers = require('../support/helpers/cozy')
const pouchHelpers = require('../support/helpers/pouch')
const { IntegrationTestHelpers } = require('../support/helpers/integration')

suite('Platform incompatibilities', () => {
  let builders, cozy, helpers

  before(configHelpers.createConfig)
  before(configHelpers.registerClient)
  beforeEach(pouchHelpers.createDatabase)
  beforeEach(cozyHelpers.deleteAll)

  afterEach(() => helpers.local.clean())
  afterEach(pouchHelpers.cleanDatabase)
  after(configHelpers.cleanConfig)

  beforeEach(async function () {
    cozy = cozyHelpers.cozy
    builders = new Builders(cozy, this.pouch)
    helpers = new IntegrationTestHelpers(this.config, this.pouch, cozy)

    await helpers.local.setupTrash()
    await helpers.remote.ignorePreviousChanges()
  })

  if (process.platform !== 'win32' && process.platform !== 'darwin') {
    test.skip(`is not tested on ${process.platform}`, () => {})
  } else {
    test('add incompatible dir and file', async () => {
      await builders.remote.dir().named('di:r').create()
      await builders.remote.file().named('fi:le').create()
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).be.empty()
    })
    test('add incompatible dir with two colons', async () => {
      await builders.remote.dir().named('d:i:r').create()
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).be.empty()
    })
    test('add compatible dir with some incompatible content', async () => {
      await helpers.remote.createTree([
        'dir/',
        'dir/file',
        'dir/fi:le',
        'dir/sub:dir/',
        'dir/sub:dir/file',
        'dir/subdir/',
        'dir/subdir/file'
      ])
      await helpers.pullAndSyncAll()

      should(await helpers.local.tree()).deepEqual([
        'dir/',
        'dir/file',
        'dir/subdir/',
        'dir/subdir/file'
      ])
    })
    test('rename incompatible -> incompatible', async () => {
      await helpers.remote.createTree(['d:ir/', 'f:ile'])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesByPath('/d:ir', {name: 'di:r'})
      await cozy.files.updateAttributesByPath('/f:ile', {name: 'fi:le'})
      await helpers.pullAndSyncAll()

      should(await helpers.local.tree()).be.empty()
    })
    test('trash & restore incompatible', async () => {
      const docs = await helpers.remote.createTree(['d:ir/', 'f:ile'])
      await helpers.pullAndSyncAll()

      await cozy.files.trashById(docs['d:ir/']._id)
      await cozy.files.trashById(docs['f:ile']._id)
      await helpers.pullAndSyncAll()

      should(await helpers.local.tree()).be.empty()
      should(await helpers.metadataTree()).be.empty()

      await cozy.files.restoreById(docs['d:ir/']._id)
      await cozy.files.restoreById(docs['f:ile']._id)
      await helpers.pullAndSyncAll()

      should(await helpers.local.tree()).be.empty()
    })

    test('destroy & recreate incompatible', async () => {
      const docs = await helpers.remote.createTree(['d:ir/', 'f:ile'])
      await helpers.pullAndSyncAll()

      await cozy.files.trashById(docs['d:ir/']._id)
      await cozy.files.trashById(docs['f:ile']._id)
      await cozy.files.destroyById(docs['d:ir/']._id)
      await cozy.files.destroyById(docs['f:ile']._id)
      await helpers.pullAndSyncAll()

      should(await helpers.local.tree()).be.empty()

      await helpers.remote.createTree(['d:ir/', 'f:ile'])
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).be.empty()
    })

    test('make compatible bottom-up', async () => {
      const docs = await helpers.remote.createTree([
        'd:ir/',
        'd:ir/sub:dir/',
        'd:ir/sub:dir/f:ile',
        'd:ir/sub:dir/subsubdir/'
      ])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesById(docs['d:ir/sub:dir/f:ile']._id, {name: 'file'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).be.empty()

      await cozy.files.updateAttributesById(docs['d:ir/']._id, {name: 'dir'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        'dir/'
      ])

      await cozy.files.updateAttributesById(docs['d:ir/sub:dir/']._id, {name: 'subdir'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        'dir/',
        'dir/subdir/',
        'dir/subdir/file',
        'dir/subdir/subsubdir/'
      ])
    })

    test('rename dir compatible -> incompatible', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/subdir/',
        'dir/subdir/file'
      ])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesById(docs['dir/']._id, {name: 'dir:'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        '/Trash/dir/',
        '/Trash/dir/subdir/',
        '/Trash/dir/subdir/file'
      ])
    })

    test('rename dir compatible -> incompatible with already incompatible content', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/sub:dir/',
        'dir/sub:dir/file'
      ])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesById(docs['dir/']._id, {name: 'dir:'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        '/Trash/dir/'
      ])
    })

    test('rename file compatible -> incompatible', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/file'
      ])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesById(docs['dir/file']._id, {name: 'fi:le'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        '/Trash/file',
        'dir/'
      ])
    })

    test('rename dir compatible -> compatible with incompatible content', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/fi:le',
        'dir/sub:dir/'
      ])
      await helpers.pullAndSyncAll()

      await cozy.files.updateAttributesById(docs['dir/']._id, {name: 'dir2'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        'dir2/'
      ])
    })

    test('move local dir with incompatible metadata & remote content', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/sub:dir/',
        'dir/sub:dir/file'
      ])
      await helpers.pullAndSyncAll()

      // Simulate local move
      const dir = await helpers._pouch.byRemoteIdAsync(docs['dir/']._id)
      const stats = {mtime: new Date(), ctime: new Date(), ino: dir.ino}
      // $FlowFixMe
      const dir2 = metadata.buildDir('dir2', stats)
      await helpers.prep.moveFolderAsync('local', dir2, dir)
      await helpers.syncAll()

      should(await helpers.remote.tree()).deepEqual([
        '.cozy_trash/',
        'dir2/',
        'dir2/sub:dir/',
        'dir2/sub:dir/file'
      ])
    })

    test('rename dir compatible -> incompatible -> compatible with compatible content', async () => {
      const docs = await helpers.remote.createTree([
        'dir/',
        'dir/file'
      ])
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        'dir/',
        'dir/file'
      ])

      await cozy.files.updateAttributesById(docs['dir/']._id, {name: 'd:ir'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        '/Trash/dir/',
        '/Trash/dir/file'
      ])

      await cozy.files.updateAttributesById(docs['dir/']._id, {name: 'dir'})
      await helpers.pullAndSyncAll()
      should(await helpers.local.tree()).deepEqual([
        // XXX: We don't restore from OS trash for now. Hence the copy.
        '/Trash/dir/',
        '/Trash/dir/file',
        'dir/',
        'dir/file'
      ])
    })
  }
})
<|endoftext|>


<commit_before>const { expect } = require('chai');
const logger = require('../../../../src/logger/index');
const app = require('../../../../src/app');
const testObjects = require('../../helpers/testObjects')(app);

const adminStudentsService = app.service('/users/admin/students');
const adminTeachersService = app.service('/users/admin/teachers');
const consentService = app.service('consents');

const { equal: equalIds } = require('../../../../src/helper/compare').ObjectId;

describe('AdminUsersService', () => {
	let server;

	before((done) => {
		server = app.listen(0, done);
	});

	after((done) => {
		server.close(done);
	});

	it('is properly registered', () => {
		expect(adminStudentsService).to.not.equal(undefined);
	});

	it('builds class display names correctly', async () => {
		const teacher = await testObjects.createTestUser({ roles: ['teacher'] }).catch((err) => {
			logger.warning('Can not create teacher', err);
		});
		const student = await testObjects.createTestUser({ roles: ['student'] }).catch((err) => {
			logger.warning('Can not create student', err);
		});

		expect(teacher).to.not.be.undefined;
		expect(student).to.not.be.undefined;

		const testClass = await testObjects.createTestClass({
			name: 'staticName',
			userIds: [student._id],
			teacherIds: [teacher._id],
		});
		expect(testClass).to.not.be.undefined;

		const gradeLevelClass = await testObjects.createTestClass({
			name: 'A',
			userIds: [student._id],
			teacherIds: [teacher._id],
			nameFormat: 'gradeLevel+name',
			gradeLevel: 2,
		}).catch((err) => {
			logger.warning('Can not create test class.', err);
		});
		expect(gradeLevelClass).to.not.be.undefined;

		const params = {
			account: {
				userId: teacher._id,
			},
		};

		const result = await adminStudentsService.find(params).catch((err) => {
			logger.warning('Can not execute adminStudentsService.find.', err);
		});

		const searchClass = (users, name) => users.some(
			(user) => (equalIds(student._id, user._id) && user.classes.includes(name)),
		);

		expect(result.data).to.not.be.undefined;
		expect(searchClass(result.data, 'staticName')).to.be.true;
		expect(searchClass(result.data, '2A')).to.be.true;
	});

	it('only shows current classes', async () => {
		const teacher = await testObjects.createTestUser({ roles: ['teacher'] });
		const student = await testObjects.createTestUser({ firstName: 'Max', roles: ['student'] });
		const currentSchool = await app.service('schools').get(teacher.schoolId);

		const { currentYear } = currentSchool;
		const lastYear = currentSchool.years.lastYear._id;

		const classPromises = [];
		classPromises.push(testObjects.createTestClass({
			name: 'classFromThisYear',
			userIds: [student._id],
			teacherIds: [teacher._id],
			year: currentYear,
		}));
		classPromises.push(testObjects.createTestClass({
			name: 'classFromLastYear',
			userIds: [student._id],
			teacherIds: [teacher._id],
			year: lastYear,
		}));
		classPromises.push(testObjects.createTestClass({
			name: 'classWithoutYear',
			userIds: [student._id],
			teacherIds: [teacher._id],
		}));

		await Promise.all(classPromises);

		const params = {
			account: {
				userId: teacher._id,
			},
		};

		const result = await adminStudentsService.find(params);

		expect(result.data).to.not.be.undefined;
		const studentResult = result.data.filter((u) => equalIds(u._id, student._id))[0];
		expect(studentResult.classes).to.include('classFromThisYear');
		expect(studentResult.classes).to.not.include('classFromLastYear');
		expect(studentResult.classes).to.include('classWithoutYear');
	});

	it('sorts students correctly', async () => {
		const teacher = await testObjects.createTestUser({ roles: ['teacher'] }).catch((err) => {
			logger.warning('Can not create teacher', err);
		});
		const student1 = await testObjects.createTestUser({
			firstName: 'Max',
			roles: ['student'],
		}).catch((err) => {
			logger.warning('Can not create student', err);
		});
		const student2 = await testObjects.createTestUser({
			firstName: 'Moritz',
			roles: ['student'],
		}).catch((err) => {
			logger.warning('Can not create student', err);
		});

		await testObjects.createTestConsent({
			userId: student1._id,
			userConsent: {
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			},
			parentConsents: [{
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			}],
		});

		expect(teacher).to.not.be.undefined;
		expect(student1).to.not.be.undefined;
		expect(student2).to.not.be.undefined;

		const testClass1 = await testObjects.createTestClass({
			name: '1a',
			userIds: [student1._id],
			teacherIds: [teacher._id],
		});
		expect(testClass1).to.not.be.undefined;
		const testClass2 = await testObjects.createTestClass({
			name: '2B',
			userIds: [student1._id],
			teacherIds: [teacher._id],
		});
		expect(testClass2).to.not.be.undefined;

		const createParams = (sortObject) => ({
			account: {
				userId: teacher._id,
			},
			$sort: sortObject,
		});

		const resultSortedByFirstName = await adminStudentsService.find(createParams({ firstName: -1 }));
		expect(resultSortedByFirstName.data.lenght > 1);
		expect(resultSortedByFirstName.data[0].firstName > resultSortedByFirstName.data[1].firstName);

		const resultSortedByClass = await adminStudentsService.find(createParams({ class: -1 }));
		expect(resultSortedByClass.data[0].class > resultSortedByClass.data[1].class);

		const sortOrder = {
			missing: 1,
			parentsAgreed: 2,
			ok: 3,
		};

		const resultSortedByConsent = await adminStudentsService.find(createParams({ consent: -1 }));
		expect(sortOrder[resultSortedByConsent.data[0].consent.consentStatus])
			.to.be.at.least(sortOrder[resultSortedByConsent.data[1].consent.consentStatus]);
	});

	it('filters students correctly', async () => {
		const teacher = await testObjects.createTestUser({ roles: ['teacher'] });
		const studentWithoutConsents = await testObjects.createTestUser({ roles: ['student'] });
		const studentWithParentConsent = await testObjects.createTestUser({
			roles: ['student'],
			birthday: '2010-01-01',
		});

		await testObjects.createTestConsent({
			userId: studentWithParentConsent._id,
			parentConsents: [{
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			}],
		});

		const studentWithConsents = await testObjects.createTestUser({ roles: ['student'] });

		await testObjects.createTestConsent({
			userId: studentWithConsents._id,
			userConsent: {
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			},
			parentConsents: [{
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			}],
		});

		const createParams = (status) => ({
			account: {
				userId: teacher._id,
			},
			query: {
				consentStatus: {
					$in: [status],
				},
			},
		});

		const resultMissing = (await adminStudentsService.find(createParams('missing'))).data;
		const idsMissing = resultMissing.map((e) => e._id.toString());
		expect(idsMissing).to.include(studentWithoutConsents._id.toString());
		expect(idsMissing).to.not.include(studentWithParentConsent._id.toString(), studentWithConsents._id.toString());

		const resultParentsAgreed = (await adminStudentsService.find(createParams('parentsAgreed'))).data;
		const idsParentsAgreed = resultParentsAgreed.map((e) => e._id.toString());
		expect(idsParentsAgreed).to.include(studentWithParentConsent._id.toString());
		expect(idsParentsAgreed).to.not.include(
			studentWithoutConsents._id.toString(),
			studentWithConsents._id.toString(),
		);

		const resultOk = (await adminStudentsService.find(createParams('ok'))).data;
		const idsOk = resultOk.map((e) => e._id.toString());
		expect(idsOk).to.include(studentWithConsents._id.toString());
		expect(idsOk).to.not.include(studentWithoutConsents._id.toString(), studentWithParentConsent._id.toString());
	});

	after(async () => {
		await testObjects.cleanup();
	});
});

describe('AdminTeachersService', () => {
	let server;

	before((done) => {
		server = app.listen(0, done);
	});

	after((done) => {
		server.close(done);
	});

	it('is properly registered', () => {
		expect(adminTeachersService).to.not.equal(undefined);
	});

	it('filters teachers correctly', async () => {
		const teacherWithoutConsent = await testObjects.createTestUser({ roles: ['teacher'] });
		const teacherWithConsent = await testObjects.createTestUser({ roles: ['teacher'] });

		await consentService.create({
			userId: teacherWithConsent._id,
			userConsent: {
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			},
		});

		const createParams = (status) => ({
			account: {
				userId: teacherWithoutConsent._id,
			},
			query: {
				consentStatus: {
					$in: [status],
				},
			},
		});

		const resultMissing = (await adminTeachersService.find(createParams('missing'))).data;
		const idsMissing = resultMissing.map((e) => e._id.toString());
		expect(idsMissing).to.include(teacherWithoutConsent._id.toString());
		expect(idsMissing).to.not.include(teacherWithConsent._id.toString());

		const resultParentsAgreed = (await adminTeachersService.find(createParams('parentsAgreed'))).data;
		expect(resultParentsAgreed).to.be.empty;

		const resultOk = (await adminTeachersService.find(createParams('ok'))).data;
		const idsOk = resultOk.map((e) => e._id.toString());
		expect(idsOk).to.include(teacherWithConsent._id.toString());
		expect(idsOk).to.not.include(teacherWithoutConsent._id.toString());
	});

	after(async () => {
		await testObjects.cleanup();
	});
});
<commit_msg>Fix tests<commit_after>const { expect } = require('chai');
const logger = require('../../../../src/logger/index');
const app = require('../../../../src/app');
const testObjects = require('../../helpers/testObjects')(app);

const adminStudentsService = app.service('/users/admin/students');
const adminTeachersService = app.service('/users/admin/teachers');
const consentService = app.service('consents');

const { equal: equalIds } = require('../../../../src/helper/compare').ObjectId;

describe('AdminUsersService', () => {
	let server;

	before((done) => {
		server = app.listen(0, done);
	});

	after((done) => {
		server.close(done);
	});

	it('is properly registered', () => {
		expect(adminStudentsService).to.not.equal(undefined);
	});

	it('builds class display names correctly', async () => {
		const teacher = await testObjects.createTestUser({ roles: ['teacher'] }).catch((err) => {
			logger.warning('Can not create teacher', err);
		});
		const student = await testObjects.createTestUser({ roles: ['student'] }).catch((err) => {
			logger.warning('Can not create student', err);
		});

		expect(teacher).to.not.be.undefined;
		expect(student).to.not.be.undefined;

		const testClass = await testObjects.createTestClass({
			name: 'staticName',
			userIds: [student._id],
			teacherIds: [teacher._id],
		});
		expect(testClass).to.not.be.undefined;

		const gradeLevelClass = await testObjects.createTestClass({
			name: 'A',
			userIds: [student._id],
			teacherIds: [teacher._id],
			nameFormat: 'gradeLevel+name',
			gradeLevel: 2,
		}).catch((err) => {
			logger.warning('Can not create test class.', err);
		});
		expect(gradeLevelClass).to.not.be.undefined;

		const params = {
			account: {
				userId: teacher._id,
			},
			query: {},
		};

		const result = await adminStudentsService.find(params).catch((err) => {
			logger.warning('Can not execute adminStudentsService.find.', err);
		});

		const searchClass = (users, name) => users.some(
			(user) => (equalIds(student._id, user._id) && user.classes.includes(name)),
		);

		expect(result.data).to.not.be.undefined;
		expect(searchClass(result.data, 'staticName')).to.be.true;
		expect(searchClass(result.data, '2A')).to.be.true;
	});

	it('only shows current classes', async () => {
		const teacher = await testObjects.createTestUser({ roles: ['teacher'] });
		const student = await testObjects.createTestUser({ firstName: 'Max', roles: ['student'] });
		const currentSchool = await app.service('schools').get(teacher.schoolId);

		const { currentYear } = currentSchool;
		const lastYear = currentSchool.years.lastYear._id;

		const classPromises = [];
		classPromises.push(testObjects.createTestClass({
			name: 'classFromThisYear',
			userIds: [student._id],
			teacherIds: [teacher._id],
			year: currentYear,
		}));
		classPromises.push(testObjects.createTestClass({
			name: 'classFromLastYear',
			userIds: [student._id],
			teacherIds: [teacher._id],
			year: lastYear,
		}));
		classPromises.push(testObjects.createTestClass({
			name: 'classWithoutYear',
			userIds: [student._id],
			teacherIds: [teacher._id],
		}));

		await Promise.all(classPromises);

		const params = {
			account: {
				userId: teacher._id,
			},
			query: {},
		};

		const result = await adminStudentsService.find(params);

		expect(result.data).to.not.be.undefined;
		const studentResult = result.data.filter((u) => equalIds(u._id, student._id))[0];
		expect(studentResult.classes).to.include('classFromThisYear');
		expect(studentResult.classes).to.not.include('classFromLastYear');
		expect(studentResult.classes).to.include('classWithoutYear');
	});

	it('sorts students correctly', async () => {
		const teacher = await testObjects.createTestUser({ roles: ['teacher'] }).catch((err) => {
			logger.warning('Can not create teacher', err);
		});
		const student1 = await testObjects.createTestUser({
			firstName: 'Max',
			roles: ['student'],
		}).catch((err) => {
			logger.warning('Can not create student', err);
		});
		const student2 = await testObjects.createTestUser({
			firstName: 'Moritz',
			roles: ['student'],
		}).catch((err) => {
			logger.warning('Can not create student', err);
		});

		await testObjects.createTestConsent({
			userId: student1._id,
			userConsent: {
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			},
			parentConsents: [{
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			}],
		});

		expect(teacher).to.not.be.undefined;
		expect(student1).to.not.be.undefined;
		expect(student2).to.not.be.undefined;

		const testClass1 = await testObjects.createTestClass({
			name: '1a',
			userIds: [student1._id],
			teacherIds: [teacher._id],
		});
		expect(testClass1).to.not.be.undefined;
		const testClass2 = await testObjects.createTestClass({
			name: '2B',
			userIds: [student1._id],
			teacherIds: [teacher._id],
		});
		expect(testClass2).to.not.be.undefined;

		const createParams = (sortObject) => ({
			account: {
				userId: teacher._id,
			},
			query: {
				$sort: sortObject,
			},
		});

		const resultSortedByFirstName = await adminStudentsService.find(createParams({ firstName: -1 }));
		expect(resultSortedByFirstName.data.lenght > 1);
		expect(resultSortedByFirstName.data[0].firstName > resultSortedByFirstName.data[1].firstName);

		const resultSortedByClass = await adminStudentsService.find(createParams({ class: -1 }));
		expect(resultSortedByClass.data[0].class > resultSortedByClass.data[1].class);

		const sortOrder = {
			missing: 1,
			parentsAgreed: 2,
			ok: 3,
		};

		const resultSortedByConsent = await adminStudentsService.find(createParams({ consent: -1 }));
		expect(sortOrder[resultSortedByConsent.data[0].consent.consentStatus])
			.to.be.at.least(sortOrder[resultSortedByConsent.data[1].consent.consentStatus]);
	});

	it('filters students correctly', async () => {
		const teacher = await testObjects.createTestUser({ roles: ['teacher'] });
		const studentWithoutConsents = await testObjects.createTestUser({ roles: ['student'] });
		const studentWithParentConsent = await testObjects.createTestUser({
			roles: ['student'],
			birthday: '2010-01-01',
		});

		await testObjects.createTestConsent({
			userId: studentWithParentConsent._id,
			parentConsents: [{
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			}],
		});

		const studentWithConsents = await testObjects.createTestUser({ roles: ['student'] });

		await testObjects.createTestConsent({
			userId: studentWithConsents._id,
			userConsent: {
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			},
			parentConsents: [{
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			}],
		});

		const createParams = (status) => ({
			account: {
				userId: teacher._id,
			},
			query: {
				consentStatus: {
					$in: [status],
				},
			},
		});

		const resultMissing = (await adminStudentsService.find(createParams('missing'))).data;
		const idsMissing = resultMissing.map((e) => e._id.toString());
		expect(idsMissing).to.include(studentWithoutConsents._id.toString());
		expect(idsMissing).to.not.include(studentWithParentConsent._id.toString(), studentWithConsents._id.toString());

		const resultParentsAgreed = (await adminStudentsService.find(createParams('parentsAgreed'))).data;
		const idsParentsAgreed = resultParentsAgreed.map((e) => e._id.toString());
		expect(idsParentsAgreed).to.include(studentWithParentConsent._id.toString());
		expect(idsParentsAgreed).to.not.include(
			studentWithoutConsents._id.toString(),
			studentWithConsents._id.toString(),
		);

		const resultOk = (await adminStudentsService.find(createParams('ok'))).data;
		const idsOk = resultOk.map((e) => e._id.toString());
		expect(idsOk).to.include(studentWithConsents._id.toString());
		expect(idsOk).to.not.include(studentWithoutConsents._id.toString(), studentWithParentConsent._id.toString());
	});

	after(async () => {
		await testObjects.cleanup();
	});
});

describe('AdminTeachersService', () => {
	let server;

	before((done) => {
		server = app.listen(0, done);
	});

	after((done) => {
		server.close(done);
	});

	it('is properly registered', () => {
		expect(adminTeachersService).to.not.equal(undefined);
	});

	it('filters teachers correctly', async () => {
		const teacherWithoutConsent = await testObjects.createTestUser({ roles: ['teacher'] });
		const teacherWithConsent = await testObjects.createTestUser({ roles: ['teacher'] });

		await consentService.create({
			userId: teacherWithConsent._id,
			userConsent: {
				form: 'digital',
				privacyConsent: true,
				termsOfUseConsent: true,
			},
		});

		const createParams = (status) => ({
			account: {
				userId: teacherWithoutConsent._id,
			},
			query: {
				consentStatus: {
					$in: [status],
				},
			},
		});

		const resultMissing = (await adminTeachersService.find(createParams('missing'))).data;
		const idsMissing = resultMissing.map((e) => e._id.toString());
		expect(idsMissing).to.include(teacherWithoutConsent._id.toString());
		expect(idsMissing).to.not.include(teacherWithConsent._id.toString());

		const resultParentsAgreed = (await adminTeachersService.find(createParams('parentsAgreed'))).data;
		expect(resultParentsAgreed).to.be.empty;

		const resultOk = (await adminTeachersService.find(createParams('ok'))).data;
		const idsOk = resultOk.map((e) => e._id.toString());
		expect(idsOk).to.include(teacherWithConsent._id.toString());
		expect(idsOk).to.not.include(teacherWithoutConsent._id.toString());
	});

	after(async () => {
		await testObjects.cleanup();
	});
});
<|endoftext|>


<commit_before>goog.provide('ol.test.renderer.canvas.TileLayer');

goog.require('ol.transform');
goog.require('ol.layer.Tile');
goog.require('ol.renderer.Map');
goog.require('ol.renderer.canvas.TileLayer');
goog.require('ol.source.XYZ');

describe('ol.renderer.canvas.TileLayer', function() {
  var img = null;
  beforeEach(function(done) {
    img = new Image(1, 1);
    img.onload = function() {
      done();
    };
    img.src = 'data:image/gif;base64,' +
      'R0lGODlhAQABAPAAAP8AAP///yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';
  });
  afterEach(function() {
    img = null;
  });

  describe('#composeFrame()', function() {
    it('uses correct draw scale when rotating (HiDPI)', function() {
      var layer = new ol.layer.Tile({
        source: new ol.source.XYZ()
      });
      var renderer = new ol.renderer.canvas.TileLayer(layer);
      renderer.renderedTiles = [];
      var frameState = {
        viewState: {
          center: [2, 3],
          projection: ol.proj.get('EPSG:3857'),
          resolution: 1,
          rotation: Math.PI
        },
        size: [10, 10],
        pixelRatio: 2,
        coordinateToPixelTransform: ol.transform.create(),
        pixelToCoordinateTransform: ol.transform.create()
      };
      renderer.getImageTransform = function() {
        return ol.transform.create();
      };
      ol.renderer.Map.prototype.calculateMatrices2D(frameState);
      var layerState = layer.getLayerState();
      var canvas = document.createElement('canvas');
      canvas.width = 200;
      canvas.height = 100;
      var context = {
        canvas: canvas,
        drawImage: sinon.spy()
      };
      renderer.renderedTiles = [{
        getTileCoord: function() {
          return [0, 0, 0];
        },
        getImage: function() {
          return img;
        }
      }];
      renderer.composeFrame(frameState, layerState, context);
      expect(context.drawImage.firstCall.args[0].width).to.be(112);
    });
  });

});
<commit_msg>Fix mockup of tile layer to keep drawImage arguments in range<commit_after>goog.provide('ol.test.renderer.canvas.TileLayer');

goog.require('ol.transform');
goog.require('ol.layer.Tile');
goog.require('ol.renderer.Map');
goog.require('ol.renderer.canvas.TileLayer');
goog.require('ol.source.XYZ');

describe('ol.renderer.canvas.TileLayer', function() {
  var img = null;
  beforeEach(function(done) {
    img = new Image(1, 1);
    img.onload = function() {
      done();
    };
    img.src = 'data:image/gif;base64,' +
      'R0lGODlhAQABAPAAAP8AAP///yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';
  });
  afterEach(function() {
    img = null;
  });

  describe('#composeFrame()', function() {
    it('uses correct draw scale when rotating (HiDPI)', function() {
      var layer = new ol.layer.Tile({
        source: new ol.source.XYZ({
          tileSize: 1
        })
      });
      var renderer = new ol.renderer.canvas.TileLayer(layer);
      renderer.renderedTiles = [];
      var frameState = {
        viewState: {
          center: [2, 3],
          projection: ol.proj.get('EPSG:3857'),
          resolution: 1,
          rotation: Math.PI
        },
        size: [10, 10],
        pixelRatio: 2,
        coordinateToPixelTransform: ol.transform.create(),
        pixelToCoordinateTransform: ol.transform.create()
      };
      renderer.getImageTransform = function() {
        return ol.transform.create();
      };
      ol.renderer.Map.prototype.calculateMatrices2D(frameState);
      var layerState = layer.getLayerState();
      var canvas = document.createElement('canvas');
      canvas.width = 200;
      canvas.height = 100;
      var context = {
        canvas: canvas,
        drawImage: sinon.spy()
      };
      renderer.renderedTiles = [{
        getTileCoord: function() {
          return [0, 0, 0];
        },
        getImage: function() {
          return img;
        }
      }];
      renderer.composeFrame(frameState, layerState, context);
      expect(context.drawImage.firstCall.args[0].width).to.be(112);
    });
  });

});
<|endoftext|>


<commit_before>'use strict';

describe('Service: Soundhandlerservice', function () {

  // load the controller's module
  beforeEach(module('emuwebApp'));

  var b64;

 /**
   *
   */
  it('should setPlayerSrc', inject(function (Soundhandlerservice, Binarydatamaniphelper) {
    b64 = Binarydatamaniphelper.base64ToArrayBuffer(msajc003_bndl.mediaFile.data);
    Soundhandlerservice.setPlayerSrc(b64);
    expect(Soundhandlerservice.player.src).toEqual('data:audio/wav;base64,' + msajc003_bndl.mediaFile.data);
  }));

 /**
   *
   */
  it('should resetPlayerSrcFromTo', inject(function (Soundhandlerservice, Binarydatamaniphelper) {
    // phantomjs does not support subarray()
    /*Soundhandlerservice.setPlayerSrc(b64);
    Soundhandlerservice.resetPlayerSrcFromTo(0,2000)
    expect(Soundhandlerservice.player.src).toEqual('data:audio/wav;base64,' + msajc003_bndl.mediaFile.data);
    no subarray in phantomjs bug */
  }));

 /**
  it('should playFromTo', inject(function (Soundhandlerservice, Binarydatamaniphelper) {
    Soundhandlerservice.setPlayerSrc(b64);
    spyOn(Soundhandlerservice, 'resetPlayerSrcFromTo');
    console.log(Soundhandlerservice.player);
    Soundhandlerservice.playFromTo(0,2000);
    expect(Soundhandlerservice.resetPlayerSrcFromTo).toHaveBeenCalled();
  }));
   *
   */
});<commit_msg>cleanup and new simple test<commit_after>'use strict';

describe('Service: Soundhandlerservice', function () {
    var scope;

    // load the controller's module
    beforeEach(module('emuwebApp'));

    beforeEach(inject(function ($rootScope) {
        scope = $rootScope.$new();
    }));

    /**
     *
     */
    it('should extractRelPartOfWav of length 0 = only header', inject(function (Soundhandlerservice) {
        Soundhandlerservice.wavJSO = parsedWavJSO;
        var cutWav = Soundhandlerservice.extractRelPartOfWav(0, 0);
        expect(cutWav.byteLength).toEqual(44);
    }));

    /**
     *
     */
/*
    it('should not play audio if wav is empty', inject(function (Soundhandlerservice) {
        // TODO: spy on decodeAndPlay function and check that it isn't called
        //spyOn(Soundhandlerservice, 'decodeAndPlay');

        Soundhandlerservice.wavJSO = parsedWavJSO;
        Soundhandlerservice.playFromTo(0,0);
        //expect(Soundhandlerservice.decodeAndPlay).toNotHaveBeenCalled();

    }));
*/

});<|endoftext|>


<commit_before>/*jshint expr: true*/
"use strict";
var chai = require("chai");
var expect = chai.expect;
chai.config.includeStack = true;
var request = require("supertest");
var alexaAppServer = require("../index");

describe("Alexa App Server with Examples & HTTPS fail checking", function() {
  var testServer;

  afterEach(function() {
    testServer.stop();
  });

  it("fails to mount due to missing HTTPS parameters", function() {
    testServer = alexaAppServer.start({
      httpsPort: 3000,
      server_root: 'invalid_examples',
      httpsEnabled: true
    });

    expect(testServer.httpsInstance).to.not.exist;
  });

  it("fails to mount due to invalid private key and certificate", function() {
    testServer = alexaAppServer.start({
      httpsPort: 6000,
      server_root: 'invalid_examples',
      httpsEnabled: true,
      privateKey: 'invalid-private-key.pem',
      certificate: 'invalid-cert.cer'
    });

    expect(testServer.httpsInstance).to.not.exist;
  });

  it("fails to mount due to invalid CA chain file", function() {
    testServer = alexaAppServer.start({
      httpsPort: 6000,
      server_root: 'invalid_examples',
      httpsEnabled: true,
      privateKey: 'private-key.pem',
      certificate: 'cert.cer',
      chain: 'invalid-cert.ca_bundle'
    });

    expect(testServer.httpsInstance).to.not.exist;
  });

  it("fails to mount due to no passphrase given", function() {
    testServer = alexaAppServer.start({
      httpsPort: 6000,
      server_root: 'invalid_examples',
      httpsEnabled: true,
      privateKey: 'private-key.pem',
      certificate: 'cert.cer',
      chain: 'cert.ca_bundle'
    });

    expect(testServer.httpsInstance).to.not.exist;
  });

  it("fails to mount due to invalid passphrase", function() {
    testServer = alexaAppServer.start({
      httpsPort: 6000,
      server_root: 'invalid_examples',
      httpsEnabled: true,
      privateKey: 'private-key.pem',
      certificate: 'cert.cer',
      chain: 'cert.ca_bundle',
      passphrase: "test321"
    });

    expect(testServer.httpsInstance).to.not.exist;
  });

  // binding to port -1 seems to behave differently on versions of node < 6
  it("fails to mount due to invalid port", function() {
    testServer = alexaAppServer.start({
      httpsPort: -1,
      server_root: 'invalid_examples',
      httpsEnabled: true,
      privateKey: 'private-key.pem',
      certificate: 'cert.cer',
      passphrase: "test123"
    });

    expect(testServer.httpsInstance).to.not.exist;
  });
});
<commit_msg>Change test back to xit() to skill failing test on earlier version of node<commit_after>/*jshint expr: true*/
"use strict";
var chai = require("chai");
var expect = chai.expect;
chai.config.includeStack = true;
var request = require("supertest");
var alexaAppServer = require("../index");

describe("Alexa App Server with Examples & HTTPS fail checking", function() {
  var testServer;

  afterEach(function() {
    testServer.stop();
  });

  it("fails to mount due to missing HTTPS parameters", function() {
    testServer = alexaAppServer.start({
      httpsPort: 3000,
      server_root: 'invalid_examples',
      httpsEnabled: true
    });

    expect(testServer.httpsInstance).to.not.exist;
  });

  it("fails to mount due to invalid private key and certificate", function() {
    testServer = alexaAppServer.start({
      httpsPort: 6000,
      server_root: 'invalid_examples',
      httpsEnabled: true,
      privateKey: 'invalid-private-key.pem',
      certificate: 'invalid-cert.cer'
    });

    expect(testServer.httpsInstance).to.not.exist;
  });

  it("fails to mount due to invalid CA chain file", function() {
    testServer = alexaAppServer.start({
      httpsPort: 6000,
      server_root: 'invalid_examples',
      httpsEnabled: true,
      privateKey: 'private-key.pem',
      certificate: 'cert.cer',
      chain: 'invalid-cert.ca_bundle'
    });

    expect(testServer.httpsInstance).to.not.exist;
  });

  it("fails to mount due to no passphrase given", function() {
    testServer = alexaAppServer.start({
      httpsPort: 6000,
      server_root: 'invalid_examples',
      httpsEnabled: true,
      privateKey: 'private-key.pem',
      certificate: 'cert.cer',
      chain: 'cert.ca_bundle'
    });

    expect(testServer.httpsInstance).to.not.exist;
  });

  it("fails to mount due to invalid passphrase", function() {
    testServer = alexaAppServer.start({
      httpsPort: 6000,
      server_root: 'invalid_examples',
      httpsEnabled: true,
      privateKey: 'private-key.pem',
      certificate: 'cert.cer',
      chain: 'cert.ca_bundle',
      passphrase: "test321"
    });

    expect(testServer.httpsInstance).to.not.exist;
  });

  // binding to port -1 seems to behave differently on versions of node < 6
  xit("fails to mount due to invalid port", function() {
    testServer = alexaAppServer.start({
      httpsPort: -1,
      server_root: 'invalid_examples',
      httpsEnabled: true,
      privateKey: 'private-key.pem',
      certificate: 'cert.cer',
      passphrase: "test123"
    });

    expect(testServer.httpsInstance).to.not.exist;
  });
});
<|endoftext|>


<commit_before>'use strict';
var assert = require('power-assert').customize({output: {maxDepth: 2}});
var sinon = require('sinon');

var stubDispatcher = require('../../mocks/isem/variable-array-dispatcher').stub;
var converterDummies = require('../../mocks/isem/csv-to-alpha-converter');
var stubConverter = converterDummies.stub;
var dummyResult = converterDummies.dummyResult;

var Store = require('../../../app/src/scripts/modules/variable-array-store').singleton;

describe('VariableArrayStore', () => {
  describe('#register()', () => {
    before(() => {
      Store.register();
    });

    it('should do Dispatcher#init()', () => {
      assert(stubDispatcher.init.callCount === 1);
    });

    it('should do Dispatcher#registerOnAddVariable()', () => {
      assert(stubDispatcher.registerOnAddVariable.callCount === 1);
    });

    it('should give the callback to arg[0] of Dispatcher#registerOnAddVariable()', () => {
      var actual = stubDispatcher.registerOnAddVariable.getCall(0).args[0];
      var expected = Store.onAddVariableCallback();
      assert(String(actual) === String(expected));
    });

    it('should do Dispatcher#registerOnImportFile()', () => {
      assert(stubDispatcher.registerOnImportFile.callCount === 1);
    });

    it('should give the callback to arg[0] of Dispatcher#registerOnImportFile()', () => {
      var actual = stubDispatcher.registerOnImportFile.getCall(0).args[0];
      var expected = Store.onImportFileCallback();
      assert(String(actual) === String(expected));
    });
  });

  describe('#onAddVariableCallback()', () => {
    var publishChange;
    before(() => {
      publishChange = sinon.stub(Store, 'publishChange');
      Store.variableArray = ['A'];
      Store.onAddVariableCallback()(null, 'B');
    });

    after(() => {
      publishChange.restore();
    });

    it('should set new variable to Store.variableArray', () => {
      assert.deepEqual(Store.variableArray, ['A', 'B']);
    });

    it('should do #publishChange()', () => {
      assert(publishChange.callCount === 1);
    });
  });

  describe('#onImportFileCallback()', () => {
    var publishChange;
    before(() => {
      publishChange = sinon.stub(Store, 'publishChange');
      Store.onImportFileCallback()(null, 'dummy');
    });

    after(() => {
      publishChange.restore();
    });

    it('should give the callbacks arg to arg[0] of Converter#convert()', () => {
      assert(stubConverter.convert.getCall(0).args[0] === 'dummy');
    });

    it('should replace variables to Store.variableArray', () => {
      assert.deepEqual(Store.variableArray, dummyResult.nodes);
    });

    it('should do #publishChange()', () => {
      assert(publishChange.callCount === 1);
    });
  });
});<commit_msg>test(variable-array-store): add test of #addChangeListener()<commit_after>'use strict';
var assert = require('power-assert').customize({output: {maxDepth: 2}});
var sinon = require('sinon');

var stubDispatcher = require('../../mocks/isem/variable-array-dispatcher').stub;
var converterDummies = require('../../mocks/isem/csv-to-alpha-converter');
var stubConverter = converterDummies.stub;
var dummyResult = converterDummies.dummyResult;

var Store = require('../../../app/src/scripts/modules/variable-array-store').singleton;

describe('VariableArrayStore', () => {
  describe('#register()', () => {
    before(() => {
      Store.register();
    });

    it('should do Dispatcher#init()', () => {
      assert(stubDispatcher.init.callCount === 1);
    });

    it('should do Dispatcher#registerOnAddVariable()', () => {
      assert(stubDispatcher.registerOnAddVariable.callCount === 1);
    });

    it('should give the callback to arg[0] of Dispatcher#registerOnAddVariable()', () => {
      var actual = stubDispatcher.registerOnAddVariable.getCall(0).args[0];
      var expected = Store.onAddVariableCallback();
      assert(String(actual) === String(expected));
    });

    it('should do Dispatcher#registerOnImportFile()', () => {
      assert(stubDispatcher.registerOnImportFile.callCount === 1);
    });

    it('should give the callback to arg[0] of Dispatcher#registerOnImportFile()', () => {
      var actual = stubDispatcher.registerOnImportFile.getCall(0).args[0];
      var expected = Store.onImportFileCallback();
      assert(String(actual) === String(expected));
    });
  });

  describe('#onAddVariableCallback()', () => {
    var publishChange;
    before(() => {
      publishChange = sinon.stub(Store, 'publishChange');
      Store.variableArray = ['A'];
      Store.onAddVariableCallback()(null, 'B');
    });

    after(() => {
      publishChange.restore();
    });

    it('should set new variable to Store.variableArray', () => {
      assert.deepEqual(Store.variableArray, ['A', 'B']);
    });

    it('should do #publishChange()', () => {
      assert(publishChange.callCount === 1);
    });
  });

  describe('#onImportFileCallback()', () => {
    var publishChange;
    before(() => {
      publishChange = sinon.stub(Store, 'publishChange');
      Store.onImportFileCallback()(null, 'dummy');
    });

    after(() => {
      publishChange.restore();
    });

    it('should give the callbacks arg to arg[0] of Converter#convert()', () => {
      assert(stubConverter.convert.getCall(0).args[0] === 'dummy');
    });

    it('should replace variables to Store.variableArray', () => {
      assert.deepEqual(Store.variableArray, dummyResult.nodes);
    });

    it('should do #publishChange()', () => {
      assert(publishChange.callCount === 1);
    });
  });

  describe('#addChangeListener()', () => {
    var dummy = 'addChangeListenerListener';
    before(() => {
      stubRootScope.$on.reset();
      Store.init();
      Store.addChangeListener(dummy);
    });

    it('should give the event name to arg[0] of $on()', () => {
      assert(stubRootScope.$on.getCall(0).args[0] === Store.constructor.CHANGE_EVENT);
    });

    it('should give the listener to arg[1] of $on()', () => {
      assert(stubRootScope.$on.getCall(0).args[1] === dummy);
    });
  });
});<|endoftext|>


<commit_before>/* global assert, process, setup, sinon, suite, test */
var entityFactory = require('../helpers').entityFactory;

suite('oculus-touch-controls', function () {
  var el;
  var component;

  setup(function (done) {
    el = this.el = entityFactory();
    el.setAttribute('oculus-touch-controls', '');
    el.addEventListener('loaded', function () {
      component = el.components['oculus-touch-controls'];
      component.controllersWhenPresent = [
        {id: 'Oculus Touch', index: 0, hand: 'left', pose: {}}
      ];
      done();
    });
  });

  suite('checkIfControllerPresent', function () {
    test('removes event listeners if controllers not present', function () {
      var addEventListenersSpy = sinon.spy(component, 'addEventListeners');
      var injectTrackedControlsSpy = sinon.spy(component, 'injectTrackedControls');
      var removeEventListenersSpy = sinon.spy(component, 'removeEventListeners');

      // Mock has not been checked previously.
      delete component.controllerPresent;

      component.checkIfControllerPresent();

      sinon.assert.notCalled(injectTrackedControlsSpy);
      sinon.assert.notCalled(addEventListenersSpy);
      sinon.assert.calledOnce(removeEventListenersSpy);
      assert.strictEqual(component.controllerPresent, false);
    });

    test('does not call removeEventListeners multiple times', function () {
      var addEventListenersSpy = sinon.spy(component, 'addEventListeners');
      var injectTrackedControlsSpy = sinon.spy(component, 'injectTrackedControls');
      var removeEventListenersSpy = sinon.spy(component, 'removeEventListeners');

      // Mock that it's been checked previously.
      component.controllerPresent = false;

      component.checkIfControllerPresent();

      sinon.assert.notCalled(injectTrackedControlsSpy);
      sinon.assert.notCalled(addEventListenersSpy);
      sinon.assert.notCalled(removeEventListenersSpy);
      assert.strictEqual(component.controllerPresent, false);
    });

    test('attach events if controller is newly present', function () {
      var addEventListenersSpy = sinon.spy(component, 'addEventListeners');
      var injectTrackedControlsSpy = sinon.spy(component, 'injectTrackedControls');
      var removeEventListenersSpy = sinon.spy(component, 'removeEventListeners');

      // Mock isControllerPresent to return true.
      el.sceneEl.systems['tracked-controls-webvr'].controllers = component.controllersWhenPresent;

      // Mock that it's never been checked previously.
      delete component.controllerPresent;

      component.checkIfControllerPresent();

      sinon.assert.calledOnce(injectTrackedControlsSpy);
      sinon.assert.calledOnce(addEventListenersSpy);
      sinon.assert.notCalled(removeEventListenersSpy);
      assert.strictEqual(component.controllerPresent, true);
    });

    test('does not add/remove event listeners if presence does not change', function () {
      var addEventListenersSpy = sinon.spy(component, 'addEventListeners');
      var injectTrackedControlsSpy = sinon.spy(component, 'injectTrackedControls');
      var removeEventListenersSpy = sinon.spy(component, 'removeEventListeners');

      // Mock isControllerPresent to return true.
      el.sceneEl.systems['tracked-controls-webvr'].controllers = component.controllersWhenPresent;

      // Mock that it's was currently present.
      component.controllerEventsActive = true;
      component.controllerPresent = true;

      component.checkIfControllerPresent();

      sinon.assert.notCalled(injectTrackedControlsSpy);
      sinon.assert.notCalled(addEventListenersSpy);
      sinon.assert.notCalled(removeEventListenersSpy);
      assert.strictEqual(component.controllerPresent, true);
    });

    test('removes event listeners if controller disappears', function () {
      var addEventListenersSpy = sinon.spy(component, 'addEventListeners');
      var injectTrackedControlsSpy = sinon.spy(component, 'injectTrackedControls');

      // Mock that it's was currently present.
      component.controllerEventsActive = true;
      component.controllerPresent = true;

      component.checkIfControllerPresent();

      sinon.assert.notCalled(injectTrackedControlsSpy);
      sinon.assert.notCalled(addEventListenersSpy);
      assert.strictEqual(component.controllerPresent, false);
    });
  });

  suite('axismove', function () {
    test('emits thumbstick moved', function (done) {
      el.sceneEl.systems['tracked-controls-webvr'].controllers = component.controllersWhenPresent;
      // Do the check.
      component.checkIfControllerPresent();
      // Set up the event details.
      const eventDetails = {axis: [0.1, 0.2], changed: [true, false]};
      // Install event handler listening for thumbstickmoved.
      this.el.addEventListener('thumbstickmoved', function (evt) {
        assert.equal(evt.detail.x, eventDetails.axis[0]);
        assert.equal(evt.detail.y, eventDetails.axis[1]);
        done();
      });
      // Emit axismove.
      this.el.emit('axismove', eventDetails);
    });

    test('does not emit thumbstickmoved if axismove has no changes', function (done) {
      el.sceneEl.systems['tracked-controls-webvr'].controllers = component.controllersWhenPresent;
      // Do the check.
      component.checkIfControllerPresent();
      // Fail purposely.
      this.el.addEventListener('thumbstickmoved', function (evt) {
        assert.fail('thumbstickmoved should not be called');
      });
      // Emit axismove with no changes.
      this.el.emit('axismove', {axis: [0.1, 0.2], changed: [false, false]});
      setTimeout(() => { done(); });
    });
  });

  suite('buttonchanged', function () {
    test('can emit triggerchanged', function (done) {
      el.sceneEl.systems['tracked-controls-webvr'].controllers = component.controllersWhenPresent;
      // Do the check.
      component.checkIfControllerPresent();
      // Prepare the event details
      const eventState = {value: 0.5, pressed: true, touched: true};
      // Install event handler listening for triggerchanged.
      el.addEventListener('triggerchanged', function (evt) {
        assert.deepEqual(evt.detail, eventState);
        done();
      });
      // Emit buttonchanged.
      el.emit('buttonchanged', {id: 1, state: eventState});
    });
  });
});
<commit_msg>Oculus Touch tests use same simplification as Go tests (#4067)<commit_after>/* global assert, process, setup, sinon, suite, test */
var entityFactory = require('../helpers').entityFactory;

suite('oculus-touch-controls', function () {
  var el;
  var component;

  setup(function (done) {
    el = this.el = entityFactory();
    el.setAttribute('oculus-touch-controls', '');
    el.addEventListener('loaded', function () {
      component = el.components['oculus-touch-controls'];
      // Initially no controllers are present
      component.controllers = [];
      // Our Mock data for enabling the controllers.
      component.controllersWhenPresent = [{
        id: 'Oculus Touch',
        index: 0,
        hand: 'left',
        pose: {}
      }];
      done();
    });
  });

  suite('checkIfControllerPresent', function () {
    var component;
    var controllerSystem;
    var addEventListenersSpy;
    var injectTrackedControlsSpy;
    var removeEventListenersSpy;

    setup(function (done) {
      component = this.el.components['oculus-touch-controls'];
      controllerSystem = this.el.sceneEl.systems['tracked-controls-webvr'];
      addEventListenersSpy = sinon.spy(component, 'addEventListeners');
      injectTrackedControlsSpy = sinon.spy(component, 'injectTrackedControls');
      removeEventListenersSpy = sinon.spy(component, 'removeEventListeners');
      done();
    });

    /**
     * Verifies that the method spy's are in the right state for a controller
     * that has been injected.
     *
     * @param {object} component - The oculus-go-controls component to verify fields.
     */
    function verifyControllerSetup (component) {
      sinon.assert.calledOnce(injectTrackedControlsSpy);
      sinon.assert.calledOnce(addEventListenersSpy);
      sinon.assert.notCalled(removeEventListenersSpy);
      assert.strictEqual(component.controllerPresent, true);
    }

    test('returns not present if no controllers on first call', function () {
      // Our current setup state is that no controllers are present. Check for presence
      // and verify that we do not find controllers or call any spy methods.
      component.checkIfControllerPresent();

      sinon.assert.notCalled(injectTrackedControlsSpy);
      sinon.assert.notCalled(addEventListenersSpy);
      sinon.assert.notCalled(removeEventListenersSpy);
      assert.strictEqual(component.controllerPresent, false);
    });

    test('attaches events if controller is newly present', function () {
      // Setup our mock controller with an initial state of no controllers present and verify
      // that we detect the controller and inject our tracked-controls component.
      controllerSystem.controllers = component.controllersWhenPresent;
      component.checkIfControllerPresent();

      verifyControllerSetup(component);
    });

    test('does not inject/attach events again if controller already present', function () {
      // Controllers are both present and already attached. No events or attachment should happen.
      controllerSystem.controllers = component.controllersWhenPresent;

      // First set up a real controller so the internal state is consistent with an already
      // present controller.
      component.checkIfControllerPresent();
      verifyControllerSetup(component);

      // Check again to verify that the already attached controller doesn't cause any side effects.
      // The counts on the spies should be exactly the same as they were prior.
      component.checkIfControllerPresent();
      verifyControllerSetup(component);
    });

    test('removes event listeners if controller disappears', function () {
      controllerSystem.controllers = component.controllersWhenPresent;

      // First set up a real controller so the internal state is consistent with an already
      // present controller.
      component.checkIfControllerPresent();
      verifyControllerSetup(component);

      // Remove the controllers and verify that everything is cleaned up correctly. We do this
      // by resetting the spy methods so we are certain only the remove is called.
      controllerSystem.controllers = [];
      injectTrackedControlsSpy.reset();
      addEventListenersSpy.reset();
      removeEventListenersSpy.reset();

      component.checkIfControllerPresent();

      sinon.assert.notCalled(injectTrackedControlsSpy);
      sinon.assert.notCalled(addEventListenersSpy);
      sinon.assert.calledOnce(removeEventListenersSpy);
      assert.strictEqual(component.controllerPresent, false);
    });
  });

  suite('axismove', function () {
    test('emits thumbstick moved', function (done) {
      el.sceneEl.systems['tracked-controls-webvr'].controllers = component.controllersWhenPresent;
      // Do the check.
      component.checkIfControllerPresent();
      // Set up the event details.
      const eventDetails = {axis: [0.1, 0.2], changed: [true, false]};
      // Install event handler listening for thumbstickmoved.
      this.el.addEventListener('thumbstickmoved', function (evt) {
        assert.equal(evt.detail.x, eventDetails.axis[0]);
        assert.equal(evt.detail.y, eventDetails.axis[1]);
        done();
      });
      // Emit axismove.
      this.el.emit('axismove', eventDetails);
    });

    test('does not emit thumbstickmoved if axismove has no changes', function (done) {
      el.sceneEl.systems['tracked-controls-webvr'].controllers = component.controllersWhenPresent;
      // Do the check.
      component.checkIfControllerPresent();
      // Fail purposely.
      this.el.addEventListener('thumbstickmoved', function (evt) {
        assert.fail('thumbstickmoved should not be called');
      });
      // Emit axismove with no changes.
      this.el.emit('axismove', {axis: [0.1, 0.2], changed: [false, false]});
      setTimeout(() => { done(); });
    });
  });

  suite('buttonchanged', function () {
    test('can emit triggerchanged', function (done) {
      el.sceneEl.systems['tracked-controls-webvr'].controllers = component.controllersWhenPresent;
      // Do the check.
      component.checkIfControllerPresent();
      // Prepare the event details
      const eventState = {value: 0.5, pressed: true, touched: true};
      // Install event handler listening for triggerchanged.
      el.addEventListener('triggerchanged', function (evt) {
        assert.deepEqual(evt.detail, eventState);
        done();
      });
      // Emit buttonchanged.
      el.emit('buttonchanged', {id: 1, state: eventState});
    });
  });
});
<|endoftext|>


<commit_before>import DatatableFactory from "ember-easy-datatable/utils/datatable-factory";
import hbs from 'htmlbars-inline-precompile';
import { moduleForComponent, test } from 'ember-qunit';
import customHelpers from '../../helpers/_custom-helpers'

moduleForComponent('easy-datatable', 'Integration | Component | Insertion', {
  integration: true,
  setup: function() {

    this.set('table', DatatableFactory.makeDatatable({
      headers: ['', 'Name', 'Value 1', 'Value 2', 'Value 3'],
      body: [
        [{isHeader: true, value: '#0'}, 'Row 0', 0, 10, 20],
        [{isHeader: true, value: '#1'}, 'Row 1', 1, 11, 21],
        [{isHeader: true, value: '#2'}, 'Row 2', 2, 12, 22],
        [{isHeader: true, value: '#3'}, 'Row 3', 3, 13, 23]
      ],

      makeDefaultRow: function () {
        var row = DatatableFactory.makeListOf(this.get('headers.cells.length'));
        row[0] = {
          isHeader: true,
          isEditable: false
        };
        return row;
      }
    }));
  },

});

test('Inserting a new row', function(assert) {
  assert.expect(5);

  this.render(hbs`{{easy-datatable table=table}}`);

  assert.deepEqual(customHelpers.getDatatableContent(),[['Row 0', '0', '10', '20'],
                                                      ['Row 1', '1', '11', '21'],
                                                      ['Row 2', '2', '12', '22'],
                                                      ['Row 3', '3', '13', '23']]);
  customHelpers.clickOnDatatableCell(1, 1);
  customHelpers.pressEscInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(),[['Row 0', '0', '10', '20'],
                                                      ['Row 1', '1', '11', '21'],
                                                      ['Row 2', '2', '12', '22'],
                                                      ['Row 3', '3', '13', '23']]
                                            ,'Nothing happens if it is not done in a row header');
  customHelpers.pressLeftKeyInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(),[['Row 0', '0', '10', '20'],
                                                      ['', '', '', ''],
                                                      ['Row 1', '1', '11', '21'],
                                                      ['Row 2', '2', '12', '22'],
                                                      ['Row 3', '3', '13', '23']]
                                            ,'Otherwise, a new empty row is added after the selected row');
  assert.deepEqual(customHelpers.getSelectedPosition(), {row: 2, column: 0}
    ,'The header of the new row is selected');
  customHelpers.clickOnDatatableCell(5, 0);
  customHelpers.pressEscInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getSelectedPosition(), {row: 6, column: 0}
    ,'Inserting the last row with a keyboard shortcut brings to the correct cell');
});

test('Inserting a new row can be prevented by setting "canInsertRows" at the table level', function (assert) {
  var self = this;
  assert.expect(2);

  this.render(hbs`{{easy-datatable table=table}}`);
  self.get('table').set('canInsertRows', false);

  assert.deepEqual(customHelpers.getDatatableContent(),[
  ['Row 0', '0', '10', '20'],
  ['Row 1', '1', '11', '21'],
  ['Row 2', '2', '12', '22'],
  ['Row 3', '3', '13', '23']]);
  customHelpers.clickOnDatatableCell(1, 0);
  customHelpers.pressEscInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'There is no row added');
});

test('It is also possible to avoid new rows at given indices', function (assert) {
  var self = this;
  assert.expect(3);

  this.render(hbs`{{easy-datatable table=table}}`);
  self.get('table.body')[2].set('cells.firstObject.canInsertRowAfter', false);

  assert.deepEqual(customHelpers.getDatatableContent(),[
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']]);
  customHelpers.clickOnDatatableCell(3, 0);
  customHelpers.pressEscInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(),[
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'There is no row added');
  customHelpers.pressUpKeyInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['', '', '', ''],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'But rows can still be inserted at other places');
});

test('Inserting a new column', function (assert) {
  assert.expect(6);

  this.render(hbs`{{easy-datatable table=table}}`);
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ]);
  customHelpers.clickOnDatatableCell(1, 1);
  customHelpers.pressEscInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'Nothing happens if it is not done in a column header');
  customHelpers.pressUpKeyInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '', '0', '10', '20'],
    ['Row 1', '', '1', '11', '21'],
    ['Row 2', '', '2', '12', '22'],
    ['Row 3', '', '3', '13', '23']
  ], 'Otherwise, a new empty column is added after the selected column');
  assert.deepEqual(customHelpers.getDatatableHeaders(), [ "", 'Name', '', 'Value 1', 'Value 2', 'Value 3']
  ,'An empty header is also added');
  assert.deepEqual(customHelpers.getSelectedPosition(), {row: 0, column: 2}
    ,'The correct header cell is selected after insertion');
  customHelpers.clickOnDatatableCell(0, 5);
  customHelpers.pressEscInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getSelectedPosition(), {row: 0, column: 6}
    ,'After inserting the last column, the correct cell is selected)');
});

test('Inserting a new column can be prevented by setting "canInsertColumns" to false at table level', function (assert) {
  var self = this;
  assert.expect(3);

  this.render(hbs`{{easy-datatable table=table}}`);

  self.get('table').set('canInsertColumns', false);

  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ]);
  customHelpers.clickOnDatatableCell(0, 1);
  customHelpers.pressEscInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'No column as been added');
  assert.deepEqual(customHelpers.getDatatableHeaders(), [ '', 'Name', 'Value 1', 'Value 2', 'Value 3']
    ,'headers have not changed');
});

test('It can also be prevented for specific columns', function (assert) {
  var self = this;
  assert.expect(4);

  this.render(hbs`{{easy-datatable table=table}}`);

  self.get('table').get('headers.cells')[2].set('canInsertColumnAfter', false);

  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ]);
  customHelpers.clickOnDatatableCell(0, 2);
  customHelpers.pressEscInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'No column as been added');
  assert.deepEqual(customHelpers.getDatatableHeaders(), [ '', 'Name', 'Value 1', 'Value 2', 'Value 3']
    ,'headers have not changed');
  customHelpers.pressRightKeyInDatatable();
  customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '', '20'],
    ['Row 1', '1', '11', '', '21'],
    ['Row 2', '2', '12', '', '22'],
    ['Row 3', '3', '13', '', '23']
  ], 'Columns can still be added in after other columns');
});

//TODO test('If option "editAfterInsertion" is set to true, the editor is shown after inserting a new row', function () {
//TODO test('If option "editAfterInsertion" is set to true, the editor is shown after inserting a new column', function () {
<commit_msg>Fixed insertion test<commit_after>import DatatableFactory from "ember-easy-datatable/utils/datatable-factory";
import hbs from 'htmlbars-inline-precompile';
import { moduleForComponent, test } from 'ember-qunit';
import customHelpers from '../../helpers/_custom-helpers'

moduleForComponent('easy-datatable', 'Integration | Component | Insertion', {
  integration: true,
  setup: function() {

    this.set('table', DatatableFactory.makeDatatable({
      headers: ['', 'Name', 'Value 1', 'Value 2', 'Value 3'],
      body: [
        [{isHeader: true, value: '#0'}, 'Row 0', 0, 10, 20],
        [{isHeader: true, value: '#1'}, 'Row 1', 1, 11, 21],
        [{isHeader: true, value: '#2'}, 'Row 2', 2, 12, 22],
        [{isHeader: true, value: '#3'}, 'Row 3', 3, 13, 23]
      ],

      makeDefaultRow: function () {
        var row = DatatableFactory.makeListOf(this.get('headers.cells.length'));
        row[0] = {
          isHeader: true,
          isEditable: false
        };
        return row;
      }
    }));
  },

});

test('Inserting a new row',async function(assert) {
  assert.expect(5);

  await this.render(hbs`{{easy-datatable table=table}}`);

  assert.deepEqual(customHelpers.getDatatableContent(),[['Row 0', '0', '10', '20'],
                                                      ['Row 1', '1', '11', '21'],
                                                      ['Row 2', '2', '12', '22'],
                                                      ['Row 3', '3', '13', '23']]);
  await customHelpers.clickOnDatatableCell(1, 1);
  await customHelpers.pressEscInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(),[['Row 0', '0', '10', '20'],
                                                      ['Row 1', '1', '11', '21'],
                                                      ['Row 2', '2', '12', '22'],
                                                      ['Row 3', '3', '13', '23']]
                                            ,'Nothing happens if it is not done in a row header');
  await customHelpers.pressLeftKeyInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(),[['Row 0', '0', '10', '20'],
                                                      ['', '', '', ''],
                                                      ['Row 1', '1', '11', '21'],
                                                      ['Row 2', '2', '12', '22'],
                                                      ['Row 3', '3', '13', '23']]
                                            ,'Otherwise, a new empty row is added after the selected row');
  assert.deepEqual(customHelpers.getSelectedPosition(), {row: 2, column: 0}
    ,'The header of the new row is selected');
  await customHelpers.clickOnDatatableCell(5, 0);
  await customHelpers.pressEscInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getSelectedPosition(), {row: 6, column: 0}
    ,'Inserting the last row with a keyboard shortcut brings to the correct cell');
});

test('Inserting a new row can be prevented by setting "canInsertRows" at the table level',async function (assert) {
  var self = this;
  assert.expect(2);

  await this.render(hbs`{{easy-datatable table=table}}`);
  self.get('table').set('canInsertRows', false);

  assert.deepEqual(customHelpers.getDatatableContent(),[
  ['Row 0', '0', '10', '20'],
  ['Row 1', '1', '11', '21'],
  ['Row 2', '2', '12', '22'],
  ['Row 3', '3', '13', '23']]);
  await customHelpers.clickOnDatatableCell(1, 0);
  await customHelpers.pressEscInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'There is no row added');
});

test('It is also possible to avoid new rows at given indices',async function (assert) {
  var self = this;
  assert.expect(3);

  await this.render(hbs`{{easy-datatable table=table}}`);
  self.get('table.body')[2].set('cells.firstObject.canInsertRowAfter', false);

  assert.deepEqual(customHelpers.getDatatableContent(),[
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']]);
  await customHelpers.clickOnDatatableCell(3, 0);
  await customHelpers.pressEscInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(),[
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'There is no row added');
  await customHelpers.pressUpKeyInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['', '', '', ''],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'But rows can still be inserted at other places');
});

test('Inserting a new column', async function (assert) {
  assert.expect(6);

  await this.render(hbs`{{easy-datatable table=table}}`);
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ]);
  await customHelpers.clickOnDatatableCell(1, 1);
  await customHelpers.pressEscInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'Nothing happens if it is not done in a column header');
  await customHelpers.pressUpKeyInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '', '0', '10', '20'],
    ['Row 1', '', '1', '11', '21'],
    ['Row 2', '', '2', '12', '22'],
    ['Row 3', '', '3', '13', '23']
  ], 'Otherwise, a new empty column is added after the selected column');
  assert.deepEqual(customHelpers.getDatatableHeaders(), [ "", 'Name', '', 'Value 1', 'Value 2', 'Value 3']
  ,'An empty header is also added');
  assert.deepEqual(customHelpers.getSelectedPosition(), {row: 0, column: 2}
    ,'The correct header cell is selected after insertion');
  await customHelpers.clickOnDatatableCell(0, 5);
  await customHelpers.pressEscInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getSelectedPosition(), {row: 0, column: 6}
    ,'After inserting the last column, the correct cell is selected)');
});

test('Inserting a new column can be prevented by setting "canInsertColumns" to false at table level',async function (assert) {
  var self = this;
  assert.expect(3);

  await this.render(hbs`{{easy-datatable table=table}}`);

  self.get('table').set('canInsertColumns', false);

  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ]);
  await customHelpers.clickOnDatatableCell(0, 1);
  await customHelpers.pressEscInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'No column as been added');
  assert.deepEqual(customHelpers.getDatatableHeaders(), [ '', 'Name', 'Value 1', 'Value 2', 'Value 3']
    ,'headers have not changed');
});

test('It can also be prevented for specific columns',async function (assert) {
  var self = this;
  assert.expect(4);

  await this.render(hbs`{{easy-datatable table=table}}`);

  self.get('table').get('headers.cells')[2].set('canInsertColumnAfter', false);

  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ]);
  await customHelpers.clickOnDatatableCell(0, 2);
  await customHelpers.pressEscInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '20'],
    ['Row 1', '1', '11', '21'],
    ['Row 2', '2', '12', '22'],
    ['Row 3', '3', '13', '23']
  ], 'No column as been added');
  assert.deepEqual(customHelpers.getDatatableHeaders(), [ '', 'Name', 'Value 1', 'Value 2', 'Value 3']
    ,'headers have not changed');
  await customHelpers.pressRightKeyInDatatable();
  await customHelpers.pressCtrlInserKeyInDatatable();
  assert.deepEqual(customHelpers.getDatatableContent(), [
    ['Row 0', '0', '10', '', '20'],
    ['Row 1', '1', '11', '', '21'],
    ['Row 2', '2', '12', '', '22'],
    ['Row 3', '3', '13', '', '23']
  ], 'Columns can still be added in after other columns');
});

//TODO test('If option "editAfterInsertion" is set to true, the editor is shown after inserting a new row', function () {
//TODO test('If option "editAfterInsertion" is set to true, the editor is shown after inserting a new column', function () {
<|endoftext|>