How to use mockProxy method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

test.js

Source:test.js Github

copy

Full Screen

1/**2 * This program is free software; you can redistribute it and/or3 * modify it under the terms of the GNU General Public License4 * as published by the Free Software Foundation; under version 25 * of the License (non-upgradable).6 *7 * This program is distributed in the hope that it will be useful,8 * but WITHOUT ANY WARRANTY; without even the implied warranty of9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the10 * GNU General Public License for more details.11 *12 * You should have received a copy of the GNU General Public License13 * along with this program; if not, write to the Free Software14 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.15 *16 * Copyright (c) 2019 (original work) Open Assessment Technologies SA ;17 */18/**19 * @author Hanna Dzmitryieva <hanna@taotesting.com>20 */21define([22 'jquery',23 'taoTests/runner/runner',24 'taoTests/runner/plugin',25 'taoTests/runner/proxy',26 'ltiTestReview/review/provider/qtiTestReviewProvider',27 'json!ltiTestReview/test/mocks/item-1.json',28 'json!ltiTestReview/test/mocks/item-2.json',29 'json!ltiTestReview/test/mocks/item-3.json',30 'json!ltiTestReview/test/mocks/item-4.json',31 'json!ltiTestReview/test/mocks/testData.json',32 'json!ltiTestReview/test/mocks/testContext.json',33 'json!ltiTestReview/test/mocks/testMap.json',34 'json!ltiTestReview/test/mocks/testResponses.json',35 'tpl!ltiTestReview/test/review/provider/qtiTestReviewProvider/navigation',36 'css!ltiTestReview/review/provider/css/qtiTestReviewProvider'37], function (38 $,39 runnerFactory,40 pluginFactory,41 proxyFactory,42 qtiTestReviewProvider,43 itemData1,44 itemData2,45 itemData3,46 itemData4,47 testData,48 testContext,49 testMap,50 testResponses,51 navigationTpl52) {53 'use strict';54 // the provider must be registered55 runnerFactory.registerProvider('qtiTestReviewProvider', qtiTestReviewProvider);56 QUnit.module('API');57 QUnit.test('module', assert => {58 assert.expect(2);59 assert.equal(typeof qtiTestReviewProvider, 'object', 'The module exposes an object');60 assert.equal(qtiTestReviewProvider.name, 'qtiTestReviewProvider', 'The provider has the expected name');61 });62 QUnit.cases.init([63 {title: 'loadAreaBroker'},64 {title: 'loadProxy'},65 {title: 'loadTestStore'},66 {title: 'install'},67 {title: 'init'},68 {title: 'render'},69 {title: 'loadItem'},70 {title: 'renderItem'},71 {title: 'unloadItem'},72 {title: 'destroy'}73 ]).test('provider API ', (data, assert) => {74 assert.expect(1);75 assert.equal(typeof qtiTestReviewProvider[data.title], 'function', `The provider exposes a ${data.title} function`);76 });77 QUnit.module('behavior');78 QUnit.cases.init([{79 title: 'default',80 proxy: 'qtiTestReviewProxy',81 plugin: 'mock1',82 config: {}83 }, {84 title: 'other proxy',85 proxy: 'installProxy',86 plugin: 'mock2',87 config: {88 proxyProvider: 'installProxy'89 }90 }]).test('install / init ', (data, assert) => {91 assert.expect(6);92 const ready = assert.async();93 const $fixture = $('#fixture-install');94 const mockProxy = {95 name: data.proxy,96 init() {97 assert.ok(true, 'The init method has been called on the proxy');98 return Promise.resolve({99 success: true100 });101 }102 };103 const mockPlugin = {104 name: data.plugin,105 install() {106 assert.ok(true, 'The install method has been called on the plugin');107 },108 init() {109 assert.ok(true, 'The init method has been called on the plugin');110 }111 };112 const config = Object.assign({113 renderTo: $fixture,114 options: {115 plugins: {116 [mockPlugin.name]: {117 foo: 'bar'118 }119 }120 }121 }, data.config || {});122 proxyFactory.registerProvider(mockProxy.name, mockProxy);123 const runner = runnerFactory('qtiTestReviewProvider', [pluginFactory(mockPlugin)], config)124 .on('ready', () => {125 const plugin = runner.getPlugin(mockPlugin.name);126 assert.notEqual(plugin, null, 'The plugin exists');127 assert.equal(typeof plugin, 'object', 'The plugin has been created');128 assert.deepEqual(plugin.getConfig(), config.options.plugins[mockPlugin.name], 'The plugin received the config');129 runner.destroy();130 })131 .on('error', err => {132 assert.pushResult({133 result: false,134 message: err135 });136 runner.destroy();137 })138 .on('destroy', ready)139 .init();140 });141 QUnit.test('init / life-cycle', assert => {142 assert.expect(13);143 const ready = assert.async();144 const $fixture = $('#fixture-init');145 const mockProxy = {146 name: 'initProxy',147 init() {148 assert.ok(true, 'The init method has been called on the proxy');149 return Promise.resolve({150 success: true151 });152 },153 getItem() {154 assert.ok(true, 'The getItem method has been called on the proxy');155 return Promise.resolve({156 success: true,157 content: {158 type: 'qti',159 data: itemData1160 },161 baseUrl: '',162 state: {}163 });164 }165 };166 const config = {167 renderTo: $fixture,168 proxyProvider: mockProxy.name169 };170 proxyFactory.registerProvider(mockProxy.name, mockProxy);171 const runner = runnerFactory('qtiTestReviewProvider', [], config)172 .on('ready', () => {173 Promise.resolve()174 .then(() => Promise.all([175 new Promise(resolve => {176 runner.on('enabletools.test', () => {177 assert.ok(true, 'Event enabletools has been triggered');178 resolve();179 });180 }),181 new Promise(resolve => {182 runner.on('enablenav.test', () => {183 assert.ok(true, 'Event enablenav has been triggered');184 resolve();185 });186 }),187 runner.loadItem('foo')188 ]))189 .then(() => {190 runner.off('.test');191 const promises = Promise.all([192 new Promise(resolve => {193 runner.on('enableitem.test', () => {194 assert.ok(true, 'Event enableitem has been triggered');195 resolve();196 });197 }),198 new Promise(resolve => {199 runner.on('enablenav.test', () => {200 assert.ok(true, 'Event enablenav has been triggered');201 resolve();202 });203 })204 ]);205 runner.trigger('resumeitem');206 return promises;207 })208 .then(() => {209 runner.off('.test');210 const promises = new Promise(resolve => {211 runner.on('disabletools.test', () => {212 assert.ok(true, 'Event disabletools has been triggered');213 resolve();214 });215 });216 runner.trigger('disableitem');217 return promises;218 })219 .then(() => {220 runner.off('.test');221 const promises = new Promise(resolve => {222 runner.on('enabletools.test', () => {223 assert.ok(true, 'Event enabletools has been triggered');224 resolve();225 });226 });227 runner.trigger('enableitem');228 return promises;229 })230 .then(() => {231 runner.off('.test');232 const promises = Promise.all([233 new Promise(resolve => {234 runner.on('disabletools.test', () => {235 assert.ok(true, 'Event disabletools has been triggered');236 resolve();237 });238 }),239 new Promise(resolve => {240 runner.on('enablenav.test', () => {241 assert.ok(true, 'Event enablenav has been triggered');242 resolve();243 });244 })245 ]);246 runner.trigger('error');247 return promises;248 })249 .then(() => {250 runner.off('.test');251 const promises = Promise.all([252 new Promise(resolve => {253 runner.on('disablenav.test', () => {254 assert.ok(true, 'Event disablenav has been triggered');255 resolve();256 });257 }),258 new Promise(resolve => {259 runner.on('disabletools.test', () => {260 assert.ok(true, 'Event disabletools has been triggered');261 resolve();262 });263 }),264 new Promise(resolve => {265 runner.on('flush.test', () => {266 assert.ok(true, 'Event flush has been triggered');267 resolve();268 });269 })270 ]);271 runner.trigger('finish');272 return promises;273 })274 .catch(err => {275 assert.pushResult({276 result: false,277 message: err278 });279 });280 })281 .on('destroy', ready)282 .init();283 });284 QUnit.test('render layout', assert => {285 assert.expect(13);286 const ready = assert.async();287 const $fixture = $('#fixture-render');288 const mockProxy = {289 name: 'renderProxy',290 init() {291 assert.ok(true, 'The init method has been called on the proxy');292 return Promise.resolve({293 success: true294 });295 }296 };297 const config = {298 renderTo: $fixture,299 proxyProvider: mockProxy.name300 };301 proxyFactory.registerProvider(mockProxy.name, mockProxy);302 const runner = runnerFactory('qtiTestReviewProvider', [], config)303 .on('ready', () => {304 const areaBroker = runner.getAreaBroker();305 Promise.resolve()306 .then(() => {307 const $container = areaBroker.getContainer();308 assert.equal($container.length, 1, 'The container exists');309 assert.equal(areaBroker.getContentArea().length, 1, 'The content area exists');310 assert.equal(areaBroker.getToolboxArea().length, 1, 'The toolbox area exists');311 assert.equal(areaBroker.getNavigationArea().length, 1, 'The navigation area exists');312 assert.equal(areaBroker.getControlArea().length, 1, 'The control area exists');313 assert.equal(areaBroker.getArea('actionsBar').length, 1, 'The actionsBar area exists');314 assert.equal(areaBroker.getPanelArea().length, 1, 'The panel area exists');315 assert.equal(areaBroker.getHeaderArea().length, 1, 'The header area exists');316 assert.equal(areaBroker.getArea('context').length, 1, 'The context area exists');317 assert.equal(areaBroker.getArea('contentWrapper').length, 1, 'The contentWrapper area exists');318 assert.equal(areaBroker.getArea('itemTool').length, 1, 'The itemTool area exists');319 return runner.destroy();320 })321 .then(() => {322 const $container = areaBroker.getContainer();323 assert.equal($container.length, 1, 'The container still exists');324 })325 .catch(err => {326 assert.ok(false, `Error in init method: ${err.message}`);327 runner.destroy();328 });329 })330 .on('destroy', ready)331 .init();332 });333 QUnit.cases.init([{334 title: 'item from testContext',335 initData: {336 success: true,337 testData: testData,338 testContext: testContext,339 testMap: testMap,340 testResponses: testResponses341 }342 }, {343 title: 'manual load',344 itemIdentifier: 'item-3',345 initData: {346 success: true347 }348 }]).test('render item ', (data, assert) => {349 assert.expect(6);350 const ready = assert.async();351 const $fixture = $('#fixture-item');352 const items = {353 'item-1': itemData1,354 'item-2': itemData2,355 'item-3': itemData3,356 'item-4': itemData4357 };358 const mockProxy = {359 name: 'itemProxy',360 init() {361 assert.ok(true, 'The init method has been called on the proxy');362 return Promise.resolve(data.initData);363 },364 getItem(itemIdentifier) {365 return Promise.resolve({366 success: true,367 content: {368 type: 'qti',369 data: items[itemIdentifier]370 },371 baseUrl: '',372 state: {}373 });374 }375 };376 const config = {377 renderTo: $fixture,378 proxyProvider: mockProxy.name379 };380 proxyFactory.registerProvider(mockProxy.name, mockProxy);381 const runner = runnerFactory('qtiTestReviewProvider', [], config)382 .on('ready', () => {383 Promise.resolve()384 .then(() => new Promise(resolve => {385 runner386 .off('.test')387 .after('renderitem.test', () => {388 assert.ok(true, 'The previewer has been rendered');389 resolve();390 });391 }))392 .then(() => {393 runner.off('.test');394 const promises = Promise.all([395 new Promise(resolve => {396 runner.on('beforeunloaditem.test', () => {397 assert.ok(true, 'Event beforeunloaditem has been triggered');398 resolve();399 });400 }),401 new Promise(resolve => {402 runner.on('disablenav.test', () => {403 assert.ok(true, 'Event disablenav has been triggered');404 resolve();405 });406 }),407 new Promise(resolve => {408 runner.on('disabletools.test', () => {409 assert.ok(true, 'Event disabletools has been triggered');410 resolve();411 });412 }),413 new Promise(resolve => {414 runner.on('unloaditem.test', () => {415 assert.ok(true, 'Event unloaditem has been triggered');416 resolve();417 });418 }),419 runner.unloadItem()420 ]);421 return promises;422 })423 .catch(err => {424 assert.pushResult({425 result: false,426 message: err427 });428 })429 .then(() => runner.destroy());430 if (data.itemIdentifier) {431 runner.loadItem(data.itemIdentifier);432 }433 })434 .on('error', err => {435 assert.pushResult({436 result: false,437 message: err438 });439 ready();440 })441 .on('destroy', ready)442 .init();443 });444 QUnit.cases.init([{445 title: 'all data provided',446 initData: {447 success: true,448 testData: testData,449 testContext: testContext,450 testMap: testMap,451 testResponses: testResponses452 }453 }, {454 title: 'empty jump table',455 initData: {456 success: true,457 testData: testData,458 testContext: testContext,459 testMap: Object.assign({}, testMap, {jumps: []}),460 testResponses: testResponses461 }462 }, {463 title: 'missing jump table',464 initData: {465 success: true,466 testData: testData,467 testContext: testContext,468 testMap: (() => {469 const {scope, parts, stats} = testMap;470 return {scope, parts, stats};471 })(),472 testResponses: testResponses473 }474 }]).test('navigate ', (data, assert) => {475 assert.expect(14);476 const ready = assert.async();477 const $fixture = $('#fixture-navigate');478 const items = {479 'item-1': itemData1,480 'item-2': itemData2,481 'item-3': itemData3,482 'item-4': itemData4483 };484 const mockProxy = {485 name: 'renderProxy',486 init() {487 assert.ok(true, 'The init method has been called on the proxy');488 return Promise.resolve(data.initData);489 },490 getItem(itemIdentifier) {491 assert.ok(true, 'The getItem method has been called on the proxy');492 return Promise.resolve({493 success: true,494 content: {495 type: 'qti',496 data: items[itemIdentifier]497 },498 baseUrl: '',499 state: {}500 });501 }502 };503 const config = {504 renderTo: $fixture,505 proxyProvider: mockProxy.name506 };507 proxyFactory.registerProvider(mockProxy.name, mockProxy);508 const runner = runnerFactory('qtiTestReviewProvider', [], config)509 .on('ready', () => {510 assert.ok(true, 'The test runner is now ready');511 })512 .on('error', err => {513 assert.pushResult({514 result: false,515 message: err516 });517 ready();518 })519 .on('destroy', ready)520 .init();521 Promise.resolve()522 .then(() => new Promise(resolve => {523 runner524 .off('.test')525 .on('renderitem.test', itemRef => {526 assert.equal(itemRef, 'item-1', 'The first item is rendered');527 resolve();528 });529 }))530 .then(() => new Promise(resolve => {531 runner532 .off('.test')533 .on('renderitem.test', itemRef => {534 assert.equal(itemRef, 'item-2', 'The second item is rendered');535 resolve();536 })537 .next();538 }))539 .then(() => new Promise(resolve => {540 runner541 .off('.test')542 .on('renderitem.test', itemRef => {543 assert.equal(itemRef, 'item-1', 'The first item is rendered again');544 resolve();545 })546 .previous();547 }))548 .then(() => new Promise(resolve => {549 runner550 .off('.test')551 .on('renderitem.test', itemRef => {552 assert.equal(itemRef, 'item-2', 'The second item is rendered again');553 resolve();554 })555 .next();556 }))557 .then(() => new Promise(resolve => {558 runner559 .off('.test')560 .on('renderitem.test', itemRef => {561 assert.equal(itemRef, 'item-1', 'The first item is rendered again');562 resolve();563 })564 .jump(0, 'item');565 }))566 .then(() => new Promise(resolve => {567 runner568 .off('.test')569 .on('renderitem.test', itemRef => {570 assert.equal(itemRef, 'item-3', 'The third item is rendered');571 resolve();572 })573 .jump(2, 'item');574 }))575 .catch(err => {576 assert.pushResult({577 result: false,578 message: err579 });580 })581 .then(() => runner.destroy());582 });583 QUnit.cases.init([{584 title: 'navigationlink',585 selector: '.navigationlink',586 area: 'sidebar'587 }, {588 title: 'answerlink',589 selector: '.answerlink',590 area: 'contentWrapper'591 }]).test('tab navigation', (data, assert) => {592 assert.expect(5);593 const ready = assert.async();594 const $fixture = $('#fixture-jumplinks');595 const mockProxy = {596 name: 'jumplinksProxy',597 init() {598 assert.ok(true, 'The init method has been called on the proxy');599 return Promise.resolve({600 success: true601 });602 }603 };604 const config = {605 renderTo: $fixture,606 proxyProvider: mockProxy.name607 };608 proxyFactory.registerProvider(mockProxy.name, mockProxy);609 const runner = runnerFactory('qtiTestReviewProvider', [], config)610 .on('ready', () => {611 const areaBroker = runner.getAreaBroker();612 const $container = areaBroker.getContainer();613 Promise.resolve()614 .then(() => {615 assert.equal($container.find(data.selector).length, 1, 'The link exists');616 $container.find(data.selector).focus();617 })618 .then(() => {619 assert.ok(areaBroker.getArea(data.area).hasClass('focused'), 'The area is focused');620 areaBroker.getArea(data.area).append('<div><a href="#" tabindex="0" id="navlink">Nav Link</a></div>');621 $container.find(data.selector).click();622 })623 .then(() => {624 assert.equal(areaBroker.getArea(data.area).has($(document.activeElement)).length, 1, 'The active element inside area after click on link');625 return runner.destroy();626 })627 .then(() => {628 const $container = areaBroker.getContainer();629 assert.equal($container.length, 1, 'The container still exists');630 })631 .catch(err => {632 assert.ok(false, `Error in init method: ${err.message}`);633 runner.destroy();634 });635 })636 .on('destroy', ready)637 .init();638 });639 QUnit.test('testmapchange event', assert => {640 assert.expect(3);641 const ready = assert.async();642 const $fixture = $('#fixture-testmapchange');643 const mockProxy = {644 name: 'testmapchangeProxy',645 init() {646 assert.ok(true, 'The init method has been called on the proxy');647 return Promise.resolve({648 success: true649 });650 }651 };652 const config = {653 renderTo: $fixture,654 proxyProvider: mockProxy.name655 };656 proxyFactory.registerProvider(mockProxy.name, mockProxy);657 const runner = runnerFactory('qtiTestReviewProvider', [], config)658 .on('ready', () => {659 assert.equal(runner.getTestMap(), null, 'No test map available yet');660 Promise.resolve()661 .then(() => new Promise(resolve => {662 runner663 .on('.test')664 .on('testmapchange.test', newTestMap => {665 assert.deepEqual(newTestMap, testMap, 'The test map has been changed');666 resolve();667 })668 .setTestMap(testMap);669 }))670 .then(() => {671 runner672 .off('.test');673 })674 .catch(err => {675 assert.pushResult({676 result: false,677 message: err678 });679 })680 .then(() => runner.on('.test').destroy());681 })682 .on('destroy', ready)683 .init();684 });685 QUnit.module('Visual');686 QUnit.test('Visual test', assert => {687 assert.expect(6);688 const ready = assert.async();689 const items = {690 'item-1': itemData1,691 'item-2': itemData2,692 'item-3': itemData3,693 'item-4': itemData4694 };695 const navigationPlugin = {696 name: 'navigation',697 install() {698 assert.ok(true, 'The install method has been called on the plugin');699 },700 init() {701 assert.ok(true, 'The init method has been called on the plugin');702 },703 render() {704 assert.ok(true, 'The render method has been called on the plugin');705 this.getAreaBroker()706 .getNavigationArea()707 .append($(navigationTpl(testMap.jumps.map(jump => Object.assign({label: `Item ${jump.position + 1}`}, jump)))))708 .on('click', e => this.getTestRunner().jump(e.target.dataset.position, 'item'));709 }710 };711 const mockProxy = {712 name: 'visualProxy',713 init() {714 assert.ok(true, 'The init method has been called on the proxy');715 return Promise.resolve({716 success: true,717 testData: testData,718 testContext: testContext,719 testMap: testMap,720 testResponses: testResponses721 });722 },723 getItem(itemIdentifier) {724 return Promise.resolve({725 success: true,726 content: {727 type: 'qti',728 data: items[itemIdentifier]729 },730 baseUrl: '',731 state: {}732 });733 }734 };735 const config = {736 renderTo: $('#visual-test'),737 proxyProvider: mockProxy.name,738 };739 proxyFactory.registerProvider(mockProxy.name, mockProxy);740 const runner = runnerFactory('qtiTestReviewProvider', [pluginFactory(navigationPlugin)], config)741 .on('ready.test', () => {742 assert.ok(true, 'The previewer is ready');743 })744 .on('renderitem.test', () => {745 runner.off('.test');746 assert.ok(true, 'The previewer has been rendered');747 ready();748 })749 .on('error', err => {750 assert.pushResult({751 result: false,752 message: err753 });754 ready();755 })756 .init();757 });...

Full Screen

Full Screen

base.genesys.spec.js

Source:base.genesys.spec.js Github

copy

Full Screen

1/* global describe beforeAll beforeEach afterEach expect it xit afterAll */2const { browser } = require('protractor');3const config = require('./lib/config');4const log = require('./lib/logger');5const veUtil = require('./lib/veUtil');6const MockProxy = require('./lib/mockProxy');7const Genesys = require('./po/genesys');8const Visitor = require('./po/visitor');9const genesysResponses = require('./lib/genesys');10const { exception } = require('winston');11const PROXY_SERVER_PORT = 9001;12const SOCKET_SERVER_PORT = 9898;13const genesysPageLocation = config.test_env.baseURL + '/static/genesys.purecloud.html';14const REDIRECT_URL = config.test_env.baseURL + '/static/index.html';15const accessToken = veUtil.getUUID();16const channelId = veUtil.getUUID();17describe('genesys page tests in iframe mode', function () {18 // prepare genesys page and visitor page instances19 const genesys = new Genesys();20 const visitor = new Visitor();21 // create proxy server22 const mockProxy = new MockProxy();23 let VISITOR_SESSION_ID;24 let visitorUrl;25 beforeAll(async function () {26 // prepare mocks27 genesysResponses.userResponse.organization.id = config.test_env.organizationId;28 genesysResponses.channels.connectUri = `ws://localhost:${SOCKET_SERVER_PORT}/`;29 genesysResponses.channels.id = channelId;30 genesysResponses.getChannels.entities[0].connectUri = `ws://localhost:${SOCKET_SERVER_PORT}/`;31 genesysResponses.getChannels.entities[0].id = channelId;32 genesysResponses.messages.entities[0].body = JSON.stringify({ interactionId: VISITOR_SESSION_ID });33 const authURLParams = veUtil.generateUrlParamters({34 response_type: 'token',35 client_id: config.test_env.clientId,36 redirect_uri: encodeURIComponent(genesysPageLocation)37 });38 const authHeader = {39 location: genesysPageLocation + '#access_token=' + accessToken + '&expires_in=86399&token_type=bearer'40 };41 // mandatory42 mockProxy.mockIt({ path: '/oauth/(.*)', method: 'GET' }, null, 302, authHeader);43 mockProxy.mockIt({ path: '/api/v2/users/me\\?expand=conversationSummary', method: 'GET' }, genesysResponses.conversationSummary);44 mockProxy.mockIt({ path: '/api/v2/users/me\\?expand=organization', method: 'GET' }, genesysResponses.userResponse);45 mockProxy.mockIt({ path: '/api/v2/users/:userId/presences/PURECLOUD', method: 'PATCH' }, genesysResponses.purecloud);46 mockProxy.mockIt({ path: '/api/v2/notifications/channels', method: 'POST' }, genesysResponses.channels);47 mockProxy.mockIt({ path: '/api/v2/notifications/channels', method: 'GET' }, genesysResponses.getChannels);48 mockProxy.mockIt({ path: '/api/v2/conversations/chats', method: 'GET' }, genesysResponses.chats[0]);49 mockProxy.mockIt({ path: '/api/v2/notifications/channels/' + channelId + '/subscriptions', method: 'GET' }, genesysResponses.subscriptions[0]);50 mockProxy.mockIt({ path: '/api/v2/notifications/channels/' + channelId + '/subscriptions', method: 'PUT' }, genesysResponses.subscriptions[0]);51 // webhook52 mockProxy.mockIt({ path: '/api/v2/conversations', method: 'GET' }, genesysResponses.conversations[0]);53 // not mandaroty54 /*55 mockProxy.mockIt({ path: '/api/v2/users/me\\?expand=chats', method: 'GET' }, genesysResponses.chats[0]);56 */57 // not used in this tests58 /*59 mockProxy.mockIt({ path: '/AGENT_PARTICIPANT_ID', method: 'GET' }, genesysResponses.participants);60 mockProxy.mockIt({ path: '/CONVERSATION_ID', method: 'GET' }, genesysResponses.conversationChat);61 */62 // start 80 port proxy server63 await mockProxy.startHttpProxyServer(PROXY_SERVER_PORT);64 // start 443 port proxy server65 await mockProxy.startSSlProxyServer(PROXY_SERVER_PORT);66 // start https server for mock responses67 await mockProxy.startHttpServer(PROXY_SERVER_PORT);68 // start socket server for mock socket connection69 await mockProxy.startSocketServer(SOCKET_SERVER_PORT);70 // authenticate and set to default db71 await veUtil.authenticate();72 await veUtil.setBrokerageProfile({73 branding:74 {75 visitorShowPrecall: false,76 enablePrecallWorkflow: false,77 inviteUrl: config.test_env.baseURL78 },79 newTheme: false,80 isPopup: false81 });82 });83 beforeEach(async function () {84 VISITOR_SESSION_ID = veUtil.getUUID();85 visitorUrl = visitor.constructUrlC2V(config.test_env, VISITOR_SESSION_ID);86 });87 afterEach(async function () {88 // close agent and visitor pages after the test89 try {90 await genesys.switchToIframe();91 await genesys.hangup.click();92 await genesys.confirm.click();93 await genesys.switchTo();94 await genesys.close();95 await visitor.close();96 } catch (e) {97 log.error(e.stack);98 }99 // close remaining pages100 Genesys.closeAllPages();101 });102 afterAll(async function () {103 // close proxy servers104 mockProxy.stopAndClean();105 });106 it('outbound call: invite visitor, agent is in iframe', async function () {107 // construct genesys url by pak, env, clientId108 const genesysUrl = genesys.constructUrl(config.test_env);109 // open genesys page110 await genesys.openAsNew(genesysUrl);111 // click start video button112 await genesys.authorized();113 // check is websocket conencted114 await mockProxy.isConnected();115 // check c2v button and click it116 await genesys.c2vAvailable();117 await genesys.startVideoButton.click();118 // check if iframe created119 await genesys.iframeCreated();120 await browser.sleep(1000);121 // get generated visitor url from genesys page122 visitorUrl = await genesys.getVisitorUrl();123 // open visitor page and join to the call124 await visitor.openAsNew(visitorUrl);125 expect(await visitor.shortUrlExpanded()).toBeTruthy();126 expect(await visitor.inWaitingState(config.test_env)).toBeTruthy();127 // switch to genesys page and verify we have local and remote video128 await genesys.switchToIframe();129 expect(await genesys.localVideoStarted()).toBeTruthy();130 await genesys.remoteVideoStarted();131 await expect(genesys.localvideo.getAttribute('readyState')).toEqual('4');132 // switch to visitor and verify we have local and remote video133 await visitor.switchTo();134 await visitor.localVideoStarted();135 expect(await visitor.localvideo.getAttribute('readyState')).toEqual('4');136 await visitor.remoteVideoStarted();137 });138 it('should accept inbound call in genesys page, visitor popup opens first', async function () {139 // set mockProxy server to response like there are an active interaction140 // replace chat mock with non-empty resp.141 genesysResponses.messages.entities[0].body = JSON.stringify({ interactionId: VISITOR_SESSION_ID });142 // mandatory143 mockProxy.mockIt({ path: '/api/v2/conversations/chats', method: 'GET' }, genesysResponses.chats[1]);144 mockProxy.mockIt({ path: '/api/v2/conversations/chats/' + genesysResponses.chats[1].entities[0].id + '/messages', method: 'GET' }, genesysResponses.messages);145 // mandatory and added for this test, not mandatory for outbound test146 mockProxy.mockIt({ path: '/api/v2/notifications/channels/' + channelId + '/subscriptions', method: 'GET' }, genesysResponses.subscriptions[1]);147 mockProxy.mockIt({ path: '/api/v2/notifications/channels/' + channelId + '/subscriptions', method: 'PUT' }, genesysResponses.subscriptions[1]);148 // not mandatory149 // mockProxy.mockIt({ path: '/api/v2/conversations/chats/' + genesysResponses.chats[1].entities[0].id, method: 'GET' }, genesysResponses.messages);150 // open visitor page151 await visitor.openAsNew(visitorUrl);152 // check visitor hang state153 expect(await visitor.shortUrlExpanded()).toBeTruthy();154 expect(await visitor.waitingToConnectOrAgent()).toBeTruthy();155 // construct genesys url by pak, env, clientId156 const genesysUrl = genesys.constructUrl(config.test_env);157 // open genesys page158 await genesys.openAsNew(genesysUrl);159 // test localstorage token160 await genesys.authorized(accessToken);161 // check if websocket conencted162 await mockProxy.isConnected();163 // check pickup button and click it164 await genesys.pickupAvailable();165 await genesys.acceptClickToVideoButton.click();166 // check if iframe created167 await genesys.iframeCreated();168 await genesys.switchToIframe();169 // check genesys page local stream170 expect(await genesys.localVideoStarted()).toBeTruthy();171 await genesys.remoteVideoStarted();172 await expect(genesys.localvideo.getAttribute('readyState')).toEqual('4');173 // switch to visitor and verify we have local and remote video174 await visitor.switchTo();175 await visitor.localVideoStarted();176 expect(await visitor.localvideo.getAttribute('readyState')).toEqual('4');177 await visitor.remoteVideoStarted();178 });179});180describe('genesys page tests in popup mode', function () {181 // prepare genesys page and visitor page instances182 const genesys = new Genesys();183 const visitor = new Visitor();184 // create proxy server185 const mockProxy = new MockProxy();186 let VISITOR_SESSION_ID;187 let visitorUrl;188 beforeAll(async function () {189 genesysResponses.userResponse.organization.id = config.test_env.organizationId;190 genesysResponses.channels.connectUri = `ws://localhost:${SOCKET_SERVER_PORT}/`;191 genesysResponses.channels.id = channelId;192 genesysResponses.getChannels.entities[0].connectUri = `ws://localhost:${SOCKET_SERVER_PORT}/`;193 genesysResponses.getChannels.entities[0].id = channelId;194 genesysResponses.messages.entities[0].body = JSON.stringify({ interactionId: VISITOR_SESSION_ID });195 const authHeader = {196 location: genesysPageLocation + '#access_token=' + accessToken + '&expires_in=86399&token_type=bearer'197 };198 mockProxy.mockIt({ path: '/oauth/(.*)', method: 'GET' }, null, 302, authHeader);199 mockProxy.mockIt({ path: '/api/v2/users/me\\?expand=conversationSummary', method: 'GET' }, genesysResponses.conversationSummary);200 mockProxy.mockIt({ path: '/api/v2/users/me\\?expand=organization', method: 'GET' }, genesysResponses.userResponse);201 mockProxy.mockIt({ path: '/api/v2/users/:userId/presences/PURECLOUD', method: 'PATCH' }, genesysResponses.purecloud);202 mockProxy.mockIt({ path: '/api/v2/notifications/channels', method: 'POST' }, genesysResponses.channels);203 mockProxy.mockIt({ path: '/api/v2/notifications/channels', method: 'GET' }, genesysResponses.getChannels);204 mockProxy.mockIt({ path: '/api/v2/conversations/chats', method: 'GET' }, genesysResponses.chats[0]);205 mockProxy.mockIt({ path: '/api/v2/notifications/channels/' + channelId + '/subscriptions', method: 'GET' }, genesysResponses.subscriptions[0]);206 mockProxy.mockIt({ path: '/api/v2/notifications/channels/' + channelId + '/subscriptions', method: 'PUT' }, genesysResponses.subscriptions[0]);207 mockProxy.mockIt({ path: '/api/v2/conversations', method: 'GET' }, genesysResponses.conversations[0]);208 await mockProxy.startHttpProxyServer(PROXY_SERVER_PORT);209 await mockProxy.startSSlProxyServer(PROXY_SERVER_PORT);210 await mockProxy.startHttpServer(PROXY_SERVER_PORT);211 await mockProxy.startSocketServer(SOCKET_SERVER_PORT);212 await veUtil.authenticate();213 await veUtil.setBrokerageProfile({214 branding:215 {216 visitorShowPrecall: false,217 enablePrecallWorkflow: false,218 inviteUrl: config.test_env.baseURL,219 redirectUrl: REDIRECT_URL220 },221 newTheme: false,222 isPopup: true223 });224 });225 beforeEach(async function () {226 VISITOR_SESSION_ID = veUtil.getUUID();227 visitorUrl = visitor.constructUrlC2V(config.test_env, VISITOR_SESSION_ID);228 });229 afterEach(async function () {230 try {231 await visitor.switchTo();232 log.debug(await browser.getCurrentUrl());233 await visitor.close();234 await genesys.close();235 } catch (e) {236 log.error(e.stack);237 }238 // close remaining pages239 Genesys.closeAllPages();240 });241 afterAll(async function () {242 // close proxy servers243 mockProxy.stopAndClean();244 });245 it('outbound call: invite visitor, open agent in popup by pickup button', async function () {246 // construct genesys url by pak, env, clientId247 const genesysUrl = genesys.constructUrl(config.test_env);248 // open genesys page249 await genesys.openAsNew(genesysUrl);250 // click start video button251 await genesys.authorized(accessToken);252 // check is websocket conencted253 await mockProxy.isConnected();254 // check c2v button and click it255 await genesys.c2vAvailable();256 await genesys.startVideoButton.click();257 await browser.sleep(1000);258 // get generated visitor url from genesys page259 visitorUrl = await genesys.getVisitorUrl();260 // open visitor page and join to the call261 await visitor.openAsNew(visitorUrl);262 // check if visitor is redirected from short url263 expect(await visitor.shortUrlExpanded()).toBeTruthy();264 expect(await visitor.inWaitingState(config.test_env)).toBeTruthy();265 await genesys.switchTo();266 // click start video session button to open agent popup267 await genesys.pickupAvailable();268 // check if popup created269 const windowsBeforePopup = await browser.getAllWindowHandles();270 await genesys.acceptClickToVideoButton.click();271 const agent = await genesys.popupCreated(windowsBeforePopup);272 // verify agent273 await agent.switchTo();274 expect(await agent.localVideoStarted()).toBeTruthy();275 await agent.remoteVideoStarted();276 await expect(agent.localvideo.getAttribute('readyState')).toEqual('4');277 // switch to visitor and verify we have local and remote video278 await visitor.switchTo();279 await visitor.localVideoStarted();280 expect(await visitor.localvideo.getAttribute('readyState')).toEqual('4');281 await visitor.remoteVideoStarted();282 // terminate session by agent red button283 await agent.switchTo();284 await agent.hangup.click();285 await agent.confirm.click();286 await visitor.switchTo();287 expect(await visitor.redirectedTo(REDIRECT_URL)).toBeTruthy();288 // except exception289 expect(agent.switchTo())290 .toThrow('NoSuchWindowError')291 .catch(function (e) { log.debug('handle exception to avoid crash', e); });292 });293 it('outbound call: invite visitor, open agent first in popup', async function () {294 // construct genesys url by pak, env, clientId295 const genesysUrl = genesys.constructUrl(config.test_env);296 // open genesys page297 await genesys.openAsNew(genesysUrl);298 // click start video button299 await genesys.authorized(accessToken);300 // check is websocket conencted301 await mockProxy.isConnected();302 // check c2v button and click it303 await genesys.c2vAvailable();304 await genesys.startVideoButton.click();305 await browser.sleep(1000);306 // get generated visitor url from genesys page307 visitorUrl = await genesys.getVisitorUrl();308 // click start video session button to open agent popup309 await genesys.StartVideoSessionAvailable();310 // check if popup created311 const windowsBeforePopup = await browser.getAllWindowHandles();312 await genesys.acceptIncomingCallButton.click();313 const agent = await genesys.popupCreated(windowsBeforePopup);314 await agent.switchTo();315 await agent.previewVideoStarted();316 // open visitor page and join to the call317 await visitor.openAsNew(visitorUrl);318 expect(await visitor.shortUrlExpanded()).toBeTruthy();319 expect(await visitor.inWaitingState(config.test_env)).toBeTruthy();320 // verify agent321 await agent.switchTo();322 expect(await agent.localVideoStarted()).toBeTruthy();323 await agent.remoteVideoStarted();324 await expect(agent.localvideo.getAttribute('readyState')).toEqual('4');325 // switch to visitor and verify we have local and remote video326 await visitor.switchTo();327 await visitor.localVideoStarted();328 expect(await visitor.localvideo.getAttribute('readyState')).toEqual('4');329 await visitor.remoteVideoStarted();330 // terminate session by agent red button331 await agent.switchTo();332 await agent.hangup.click();333 await agent.confirm.click();334 await visitor.switchTo();335 expect(await visitor.redirectedTo(REDIRECT_URL)).toBeTruthy();336 // except exception337 expect(agent.switchTo())338 .toThrow('NoSuchWindowError')339 .catch(function (e) { log.debug('handle exception to avoid crash', e); });340 });341 it('inbound call: create mocked invitation, use pickup button, agent is in popup', async function () {342 // set mockProxy server to response like there are an active interaction343 // replace chat mock with non-empty resp.344 genesysResponses.messages.entities[0].body = JSON.stringify({ interactionId: VISITOR_SESSION_ID });345 // mandatory346 mockProxy.mockIt({ path: '/api/v2/conversations/chats', method: 'GET' }, genesysResponses.chats[1]);347 mockProxy.mockIt({ path: '/api/v2/conversations/chats/' + genesysResponses.chats[1].entities[0].id + '/messages', method: 'GET' }, genesysResponses.messages);348 // mandatory and added for this test, not mandatory for outbound test349 mockProxy.mockIt({ path: '/api/v2/notifications/channels/' + channelId + '/subscriptions', method: 'GET' }, genesysResponses.subscriptions[1]);350 mockProxy.mockIt({ path: '/api/v2/notifications/channels/' + channelId + '/subscriptions', method: 'PUT' }, genesysResponses.subscriptions[1]);351 // not mandatory352 // mockProxy.mockIt({ path: '/api/v2/conversations/chats/' + genesysResponses.chats[1].entities[0].id, method: 'GET' }, genesysResponses.messages);353 // open visitor page354 await visitor.openAsNew(visitorUrl);355 // check visitor hang state356 expect(await visitor.shortUrlExpanded()).toBeTruthy();357 expect(await visitor.waitingToConnectOrAgent()).toBeTruthy();358 // construct genesys url by pak, env, clientId359 const genesysUrl = genesys.constructUrl(config.test_env);360 // open genesys page361 await genesys.openAsNew(genesysUrl);362 // test localstorage token363 await genesys.authorized(accessToken);364 // check if websocket conencted365 await mockProxy.isConnected();366 // check pickup button and click it367 await genesys.pickupAvailable();368 // check if popup created369 const windowsBeforePopup = await browser.getAllWindowHandles();370 await genesys.acceptClickToVideoButton.click();371 const agent = await genesys.popupCreated(windowsBeforePopup);372 // switch to agent popup373 await agent.switchTo();374 expect(await agent.localVideoStarted()).toBeTruthy();375 await agent.remoteVideoStarted();376 await expect(agent.localvideo.getAttribute('readyState')).toEqual('4');377 // switch to visitor and verify we have local and remote video378 await visitor.switchTo();379 await visitor.localVideoStarted();380 expect(await visitor.localvideo.getAttribute('readyState')).toEqual('4');381 await visitor.remoteVideoStarted();382 // terminate session by agent red button383 await agent.switchTo();384 await agent.hangup.click();385 await agent.confirm.click();386 await visitor.switchTo();387 await visitor.redirectedTo(REDIRECT_URL);388 // except exception389 expect(agent.switchTo())390 .toThrow('NoSuchWindowError')391 .catch(function (e) { log.debug('handle exception to avoid crash', e); });392 });...

Full Screen

Full Screen

PlayerTest.js

Source:PlayerTest.js Github

copy

Full Screen

1var MockProxy = require('../../MockProxy.js');2var Player = require('../../../../src/client/model/board/Player.js');3var ResourceType = require('../../../../src/client/model/ResourceType.js');4var catan = require('byu-catan');5var hexgrid = catan.models.hexgrid;6var HexLocation = hexgrid.HexLocation;7var EdgeDirection = hexgrid.EdgeDirection;8var EdgeLocation = hexgrid.EdgeLocation;9var playerTestCases = require('./PlayerTestCases.json');10var assert = require('chai').assert;11suite('PlayerTests', function() {12 var canBuyTestCases = playerTestCases[0];13 suite(canBuyTestCases.suite, function() {14 canBuyTestCases.testCases.forEach(function(testCase) {15 suite(testCase.description, function() {16 var player;17 setup(function() {18 var mockProxy = new MockProxy();19 player = new Player(mockProxy, testCase.input);20 });21 test('#canBuyRoad()', function() {22 assert.equal(testCase.output.canBuyRoad, player.canBuyRoad());23 });24 test('#canBuySettlement()', function() {25 assert.equal(testCase.output.canBuySettlement, player.canBuySettlement());26 });27 test('#canBuyCity()', function() {28 assert.equal(testCase.output.canBuyCity, player.canBuyCity());29 });30 test('#canBuyDevCard()', function() {31 assert.equal(testCase.output.canBuyDevCard, player.canBuyDevCard());32 });33 });34 });35 });36 var canPlayTestCases = playerTestCases[1];37 suite(canPlayTestCases.suite, function() {38 canPlayTestCases.testCases.forEach(function(testCase) {39 suite(testCase.description, function() {40 var player;41 setup(function() {42 var mockProxy = new MockProxy();43 player = new Player(mockProxy, testCase.input);44 });45 test('#canPlayYearOfPlenty()', function() {46 assert.equal(testCase.output.canPlayYearOfPlenty, player.canPlayYearOfPlenty());47 });48 test('#canPlayMonopoly()', function() {49 assert.equal(testCase.output.canPlayMonopoly, player.canPlayMonopoly());50 });51 test('#canPlaySoldier()', function() {52 assert.equal(testCase.output.canPlaySoldier, player.canPlaySoldier());53 });54 test('#canPlayRoadBuilding()', function() {55 assert.equal(testCase.output.canPlayRoadBuilding, player.canPlayRoadBuilding());56 });57 });58 });59 });60 var canPlayMonumentTestCases = playerTestCases[2];61 suite(canPlayMonumentTestCases.suite, function() {62 canPlayMonumentTestCases.testCases.forEach(function(testCase) {63 suite(testCase.description, function() {64 var player;65 setup(function() {66 var mockProxy = new MockProxy();67 player = new Player(mockProxy, testCase.input);68 });69 test('#canPlayMonument())', function() {70 assert.equal(testCase.output.canPlayMonument, player.canPlayMonument());71 });72 });73 });74 });75 var canMaritimeTradeTestCases = playerTestCases[3];76 suite(canMaritimeTradeTestCases.suite, function() {77 canMaritimeTradeTestCases.testCases.forEach(function(testCase) {78 suite(testCase.description, function() {79 var player;80 setup(function() {81 var mockProxy = new MockProxy();82 player = new Player(mockProxy, testCase.input);83 });84 for (var resource in testCase.output.canMaritimeTrade) {85 test('#canMaritimeTrade()', function() {86 assert.equal(testCase.output.canMaritimeTrade[resource], player.canMaritimeTrade(resource, testCase.ratios[resource]));87 });88 }89 test('#getMaritimeGiveOptions()', function() {90 assert.deepEqual(testCase.output.getMaritimeGiveOptions, player.getMaritimeGiveOptions(testCase.ratios));91 });92 });93 });94 });95 var hasToDiscardTests = playerTestCases[4];96 suite(hasToDiscardTests.suite, function() {97 hasToDiscardTests.testCases.forEach(function(testCase) {98 suite(testCase.description, function() {99 var player;100 setup(function() {101 var mockProxy = new MockProxy();102 player = new Player(mockProxy, testCase.input);103 });104 test('#hasToDiscard()', function() {105 assert.equal(testCase.output.hasToDiscard, player.hasToDiscard());106 });107 });108 });109 });110 suite('functions that talk to the proxy', function() {111 var mockProxy;112 var player;113 var randomIndex = -1992;114 setup(function() {115 mockProxy = new MockProxy();116 var testData = {117 "MAX_GAME_POINTS": 10,118 "resources": {119 "brick": 14,120 "wood": 13,121 "sheep": 15,122 "wheat": 10,123 "ore": 8124 },125 "oldDevCards": {126 "yearOfPlenty": 0,127 "monopoly": 0,128 "soldier": 2,129 "roadBuilding": 0,130 "monument": 1131 },132 "newDevCards": {133 "yearOfPlenty": 0,134 "monopoly": 0,135 "soldier": 1,136 "roadBuilding": 1,137 "monument": 0138 },139 "roads": 8,140 "cities": 2,141 "settlements": 4,142 "soldiers": 1,143 "victoryPoints": 7,144 "monuments": 0,145 "longestRoad": true,146 "largestArmy": false,147 "playedDevCard": true,148 "discarded": false,149 "playerID": 71,150 "orderNumber": 0,151 "name": "Sam",152 "color": "orange"153 };154 player = new Player(mockProxy, testData, randomIndex);155 });156 test('#buyDevCard()', function() {157 var expected = {158 "type": "JSON",159 "template": {160 "type": "buyDevCard",161 "playerIndex": randomIndex162 }163 };164 player.buyDevCard();165 assert.deepEqual(expected.template, mockProxy.lastCommand.getData());166 });167 test('#yearOfPlenty()', function() {168 var resource1 = ResourceType.BRICK;169 var resource2 = ResourceType.SHEEP;170 var expected = {171 "type": "JSON",172 "template": {173 "type": "Year_of_Plenty",174 "playerIndex": randomIndex,175 "resource1": resource1,176 "resource2": resource2177 }178 };179 player.yearOfPlenty(resource1, resource2);180 assert.deepEqual(expected.template, mockProxy.lastCommand.getData());181 });182 test('#roadBuilding()', function() {183 var x1 = -4;184 var y1 = 2;185 var direction1 = EdgeDirection.S;186 var edge1 = new EdgeLocation(new HexLocation(x1, y1), direction1);187 var x2 = 3;188 var y2 = -1;189 var direction2 = EdgeDirection.N;190 var edge2 = new EdgeLocation(new HexLocation(x2, y2), direction2);191 var expected = {192 "type": "JSON",193 "template": {194 "type": "Road_Building",195 "playerIndex": randomIndex,196 "spot1": {197 "x": x1,198 "y": y1,199 "direction": "S"200 },201 "spot2": {202 "x": x2,203 "y": y2,204 "direction": "N"205 }206 }207 };208 player.roadBuilding(edge1, edge2);209 assert.deepEqual(mockProxy.lastCommand.getData(), expected.template);210 });211 test('#playSoldier()', function() {212 var victimIndex = 21;213 var x = 3;214 var y = 4;215 var hexLocation = new HexLocation(x, y);216 var expected = {217 "type": "JSON",218 "template": {219 "type": "Soldier",220 "playerIndex": randomIndex,221 "victimIndex": victimIndex,222 "location": {223 "x": x,224 "y": y225 }226 }227 };228 player.playSoldier(hexLocation, victimIndex);229 assert.deepEqual(mockProxy.lastCommand.getData(), expected.template);230 });231 test('#monopoly()', function() {232 var resourceType = ResourceType.WHEAT;233 var expected = {234 "type": "JSON",235 "template": {236 "type": "Monopoly",237 "resource": resourceType,238 "playerIndex": randomIndex239 }240 };241 player.monopoly(resourceType);242 assert.deepEqual(expected.template, mockProxy.lastCommand.getData());243 });244 test('#playMonument()', function() {245 var expected = {246 "type": "JSON",247 "template": {248 "type": "Monument",249 "playerIndex": randomIndex250 }251 };252 player.playMonument();253 assert.deepEqual(expected.template, mockProxy.lastCommand.getData());254 });255 test('#offerTrade()', function() {256 var brick = 1;257 var ore = 2;258 var sheep = 0;259 var wheat = 0;260 var wood = 10;261 var receiver = 3;262 var expected = {263 "type": "JSON",264 "template": {265 "type": "offerTrade",266 "playerIndex": randomIndex,267 "offer": {268 "brick": brick,269 "ore": ore,270 "sheep": sheep,271 "wheat": wheat,272 "wood": wood273 },274 "receiver": receiver275 }276 };277 player.offerTrade(receiver, brick, ore, sheep, wheat, wood);278 assert.deepEqual(expected.template, mockProxy.lastCommand.getData());279 });280 test('#acceptTrade()', function() {281 var willAccept = true;282 var expected = {283 "type": "JSON",284 "template": {285 "type": "acceptTrade",286 "playerIndex": randomIndex,287 "willAccept": willAccept288 }289 };290 player.acceptTrade(willAccept);291 assert.deepEqual(expected.template, mockProxy.lastCommand.getData());292 });293 test('#maritimeTrade()', function() {294 var ratio = 3;295 var inputResource = ResourceType.WHEAT;296 var outputResource = ResourceType.WOOD;297 var expected = {298 "type": "JSON",299 "template": {300 "type": "maritimeTrade",301 "playerIndex": randomIndex,302 "ratio": ratio,303 "inputResource": inputResource,304 "outputResource": outputResource305 }306 };307 player.maritimeTrade(ratio, inputResource, outputResource);308 assert.deepEqual(expected.template, mockProxy.lastCommand.getData());309 });310 test('#discardCards()', function() {311 var brick = 0;312 var ore = 2;313 var sheep = 3;314 var wheat = 1;315 var wood = 0;316 var expected = {317 "type": "JSON",318 "template": {319 "type": "discardCards",320 "playerIndex": randomIndex,321 "discardedCards": {322 "brick": brick,323 "ore": ore,324 "sheep": sheep,325 "wheat": wheat,326 "wood": wood327 }328 }329 };330 player.discardCards(brick, ore, sheep, wheat, wood);331 assert.deepEqual(expected.template, mockProxy.lastCommand.getData());332 });333 });...

Full Screen

Full Screen

ProxyCollection.spec.js

Source:ProxyCollection.spec.js Github

copy

Full Screen

...8 return mock;9 };10 var mocks, collection;11 beforeEach(function() {12 mocks = [mockProxy(), mockProxy(), mockProxy()];13 collection = new tabris.ProxyCollection(mocks);14 });15 it("maps proxies to numeric fields", function() {16 expect(collection[0]).toBe(mocks[0]);17 expect(collection[1]).toBe(mocks[1]);18 expect(collection[2]).toBe(mocks[2]);19 });20 it("sets length value", function() {21 expect(collection.length).toBe(3);22 });23 it("first()", function() {24 expect(collection.first()).toBe(mocks[0]);25 });26 it("last()", function() {27 expect(collection.last()).toBe(mocks[2]);28 });29 it("toArray()", function() {30 var arr1 = collection.toArray();31 var arr2 = collection.toArray();32 expect(arr1).toEqual(mocks);33 expect(arr2).toEqual(mocks);34 expect(arr1).not.toBe(arr2);35 });36 it("forEach()", function() {37 var callback = jasmine.createSpy();38 collection.forEach(callback);39 expect(callback).toHaveBeenCalledWith(mocks[0], 0, collection);40 expect(callback).toHaveBeenCalledWith(mocks[1], 1, collection);41 expect(callback).toHaveBeenCalledWith(mocks[2], 2, collection);42 });43 it("indexOf()", function() {44 expect(collection.indexOf(mocks[0])).toBe(0);45 expect(collection.indexOf(mocks[1])).toBe(1);46 expect(collection.indexOf(mocks[2])).toBe(2);47 expect(collection.indexOf(null)).toBe(-1);48 });49 describe("filter()", function() {50 it("with callback", function() {51 expect(collection.filter(function(proxy) {52 return proxy !== mocks[1];53 }).toArray()).toEqual([mocks[0], mocks[2]]);54 });55 it("with type selector", function() {56 mocks[0].type = "Foo";57 mocks[1].type = "Bar";58 mocks[2].type = "Foo";59 expect(collection.filter("Foo").toArray()).toEqual([mocks[0], mocks[2]]);60 });61 it("with * selector", function() {62 mocks[0].type = "Foo";63 mocks[1].type = "Bar";64 mocks[2].type = "Foo";65 expect(collection.filter("*").toArray()).toEqual(mocks);66 });67 it("with # selectors", function() {68 mocks[0].id = "foo";69 mocks[1].id = "bar";70 mocks[2].id = "bar";71 expect(collection.filter("#bar").toArray()).toEqual([mocks[1], mocks[2]]);72 });73 });74 describe("delegation:", function() {75 it("set() is delegated", function() {76 collection.set("foo", "bar");77 expect(mocks[0].set).toHaveBeenCalledWith("foo", "bar");78 expect(mocks[1].set).toHaveBeenCalledWith("foo", "bar");79 expect(mocks[2].set).toHaveBeenCalledWith("foo", "bar");80 });81 it("set() returns collection", function() {82 expect(collection.set("foo", "bar")).toBe(collection);83 });84 it("animate() is delegated", function() {85 var props = {foo: "bar"};86 var options = {delay: 3000};87 collection.animate(props, options);88 expect(mocks[0].animate).toHaveBeenCalledWith(props, options);89 expect(mocks[1].animate).toHaveBeenCalledWith(props, options);90 expect(mocks[2].animate).toHaveBeenCalledWith(props, options);91 });92 it("animate() returns collection", function() {93 expect(collection.animate({}, {})).toBe(collection);94 });95 it("on() is delegated", function() {96 var listener = function() {};97 collection.on("foo", listener);98 expect(mocks[0].on).toHaveBeenCalledWith("foo", listener);99 expect(mocks[1].on).toHaveBeenCalledWith("foo", listener);100 expect(mocks[2].on).toHaveBeenCalledWith("foo", listener);101 });102 it("on() returns collection", function() {103 expect(collection.on("foo", function() {})).toBe(collection);104 });105 it("off() is delegated", function() {106 var listener = function() {};107 collection.off("foo", listener);108 expect(mocks[0].off).toHaveBeenCalledWith("foo", listener);109 expect(mocks[1].off).toHaveBeenCalledWith("foo", listener);110 expect(mocks[2].off).toHaveBeenCalledWith("foo", listener);111 });112 it("off() returns collection", function() {113 expect(collection.off("foo", function() {})).toBe(collection);114 });115 it("dispose() is delegated", function() {116 collection.dispose();117 expect(mocks[0].dispose).toHaveBeenCalled();118 expect(mocks[1].dispose).toHaveBeenCalled();119 expect(mocks[2].dispose).toHaveBeenCalled();120 });121 it("dispose() returns undefined", function() {122 expect(collection.dispose()).toBeUndefined();123 });124 it("get() is delegated to first", function() {125 mocks[0].get.and.returnValue("foo");126 expect(collection.get("bar")).toBe("foo");127 expect(mocks[0].get).toHaveBeenCalledWith("bar");128 });129 it("get() returns undefined for empty collection", function() {130 expect((new tabris.ProxyCollection([])).get("foo")).toBeUndefined();131 });132 it("parent() returns all parents", function() {133 var parents = [mockProxy(), mockProxy()];134 mocks[0].parent.and.returnValue(parents[0]);135 mocks[2].parent.and.returnValue(parents[1]);136 expect(collection.parent().toArray()).toEqual(parents);137 });138 it("parent() returns only unique parents", function() {139 var parents = [mockProxy(), mockProxy()];140 mocks[0].parent.and.returnValue(parents[0]);141 mocks[1].parent.and.returnValue(parents[0]);142 mocks[2].parent.and.returnValue(parents[1]);143 expect(collection.parent().toArray()).toEqual(parents);144 });145 it("parent() returns undefined for empty collection", function() {146 expect((new tabris.ProxyCollection([])).parent()).toBeUndefined();147 });148 it("appendTo(parent) calls parent.append", function() {149 var parent = mockProxy();150 collection.appendTo(parent);151 expect(parent.append).toHaveBeenCalledWith(collection);152 });153 it("children() returns children from all in collection", function() {154 var children = [mockProxy(), mockProxy(), mockProxy(), mockProxy()];155 mocks[0]._children = children.slice(0, 2);156 mocks[2]._children = children.slice(2, 4);157 expect(collection.children().toArray()).toEqual(children);158 });159 it("children() with matcher returns children from all in collection", function() {160 var children = [mockProxy(), mockProxy(), mockProxy(), mockProxy()];161 children[0].type = children[2].type = "Foo";162 mocks[0]._children = children.slice(0, 2);163 mocks[2]._children = children.slice(2, 4);164 expect(collection.children("Foo").toArray()).toEqual([children[0], children[2]]);165 });166 it("find() returns descendants from all proxies in collection", function() {167 var children = [mockProxy(), mockProxy(), mockProxy(), mockProxy()];168 mocks[0]._children = [children[0]];169 mocks[2]._children = [children[1]];170 children[1]._children = children.slice(2, 4);171 expect(collection.find("*").toArray().length).toEqual(children.length);172 expect(collection.find("*").toArray()).toEqual(children);173 });174 it("find() returns no duplicates", function() {175 var children = [mockProxy(), mockProxy(), mockProxy(), mockProxy()];176 mocks[0]._children = [children[0]];177 children[0]._children = [children[1]];178 children[1]._children = [children[2]];179 children[2]._children = [children[3]];180 var result = collection.find("*").find("*");181 expect(result.length).toBe(3);182 expect(result.indexOf(children[1])).not.toBe(-1);183 expect(result.indexOf(children[2])).not.toBe(-1);184 expect(result.indexOf(children[3])).not.toBe(-1);185 });186 });...

Full Screen

Full Screen

3603.js

Source:3603.js Github

copy

Full Screen

...8 return mock;9 };10 var mocks, collection;11 beforeEach(function() {12 mocks = [mockProxy(), mockProxy(), mockProxy()];13 collection = new tabris.ProxyCollection(mocks);14 });15 it("maps proxies to numeric fields", function() {16 expect(collection[0]).toBe(mocks[0]);17 expect(collection[1]).toBe(mocks[1]);18 expect(collection[2]).toBe(mocks[2]);19 });20 it("sets length value", function() {21 expect(collection.length).toBe(3);22 });23 it("first()", function() {24 expect(collection.first()).toBe(mocks[0]);25 });26 it("last()", function() {27 expect(collection.last()).toBe(mocks[2]);28 });29 it("toArray()", function() {30 var arr1 = collection.toArray();31 var arr2 = collection.toArray();32 expect(arr1).toEqual(mocks);33 expect(arr2).toEqual(mocks);34 expect(arr1).not.toBe(arr2);35 });36 it("forEach()", function() {37 var callback = jasmine.createSpy();38 collection.forEach(callback);39 expect(callback).toHaveBeenCalledWith(mocks[0], 0, collection);40 expect(callback).toHaveBeenCalledWith(mocks[1], 1, collection);41 expect(callback).toHaveBeenCalledWith(mocks[2], 2, collection);42 });43 it("indexOf()", function() {44 expect(collection.indexOf(mocks[0])).toBe(0);45 expect(collection.indexOf(mocks[1])).toBe(1);46 expect(collection.indexOf(mocks[2])).toBe(2);47 expect(collection.indexOf(null)).toBe(-1);48 });49 describe("filter()", function() {50 it("with callback", function() {51 expect(collection.filter(function(proxy) {52 return proxy !== mocks[1];53 }).toArray()).toEqual([mocks[0], mocks[2]]);54 });55 it("with type selector", function() {56 mocks[0].type = "Foo";57 mocks[1].type = "Bar";58 mocks[2].type = "Foo";59 expect(collection.filter("Foo").toArray()).toEqual([mocks[0], mocks[2]]);60 });61 it("with * selector", function() {62 mocks[0].type = "Foo";63 mocks[1].type = "Bar";64 mocks[2].type = "Foo";65 expect(collection.filter("*").toArray()).toEqual(mocks);66 });67 it("with # selectors", function() {68 mocks[0].id = "foo";69 mocks[1].id = "bar";70 mocks[2].id = "bar";71 expect(collection.filter("#bar").toArray()).toEqual([mocks[1], mocks[2]]);72 });73 });74 describe("delegation:", function() {75 it("set() is delegated", function() {76 collection.set("foo", "bar");77 expect(mocks[0].set).toHaveBeenCalledWith("foo", "bar");78 expect(mocks[1].set).toHaveBeenCalledWith("foo", "bar");79 expect(mocks[2].set).toHaveBeenCalledWith("foo", "bar");80 });81 it("set() returns collection", function() {82 expect(collection.set("foo", "bar")).toBe(collection);83 });84 it("animate() is delegated", function() {85 var props = {foo: "bar"};86 var options = {delay: 3000};87 collection.animate(props, options);88 expect(mocks[0].animate).toHaveBeenCalledWith(props, options);89 expect(mocks[1].animate).toHaveBeenCalledWith(props, options);90 expect(mocks[2].animate).toHaveBeenCalledWith(props, options);91 });92 it("animate() returns collection", function() {93 expect(collection.animate({}, {})).toBe(collection);94 });95 it("on() is delegated", function() {96 var listener = function() {};97 collection.on("foo", listener);98 expect(mocks[0].on).toHaveBeenCalledWith("foo", listener);99 expect(mocks[1].on).toHaveBeenCalledWith("foo", listener);100 expect(mocks[2].on).toHaveBeenCalledWith("foo", listener);101 });102 it("on() returns collection", function() {103 expect(collection.on("foo", function() {})).toBe(collection);104 });105 it("off() is delegated", function() {106 var listener = function() {};107 collection.off("foo", listener);108 expect(mocks[0].off).toHaveBeenCalledWith("foo", listener);109 expect(mocks[1].off).toHaveBeenCalledWith("foo", listener);110 expect(mocks[2].off).toHaveBeenCalledWith("foo", listener);111 });112 it("off() returns collection", function() {113 expect(collection.off("foo", function() {})).toBe(collection);114 });115 it("dispose() is delegated", function() {116 collection.dispose();117 expect(mocks[0].dispose).toHaveBeenCalled();118 expect(mocks[1].dispose).toHaveBeenCalled();119 expect(mocks[2].dispose).toHaveBeenCalled();120 });121 it("dispose() returns undefined", function() {122 expect(collection.dispose()).toBeUndefined();123 });124 it("get() is delegated to first", function() {125 mocks[0].get.and.returnValue("foo");126 expect(collection.get("bar")).toBe("foo");127 expect(mocks[0].get).toHaveBeenCalledWith("bar");128 });129 it("get() returns undefined for empty collection", function() {130 expect((new tabris.ProxyCollection([])).get("foo")).toBeUndefined();131 });132 it("parent() returns all parents", function() {133 var parents = [mockProxy(), mockProxy()];134 mocks[0].parent.and.returnValue(parents[0]);135 mocks[2].parent.and.returnValue(parents[1]);136 expect(collection.parent().toArray()).toEqual(parents);137 });138 it("parent() returns only unique parents", function() {139 var parents = [mockProxy(), mockProxy()];140 mocks[0].parent.and.returnValue(parents[0]);141 mocks[1].parent.and.returnValue(parents[0]);142 mocks[2].parent.and.returnValue(parents[1]);143 expect(collection.parent().toArray()).toEqual(parents);144 });145 it("parent() returns undefined for empty collection", function() {146 expect((new tabris.ProxyCollection([])).parent()).toBeUndefined();147 });148 it("appendTo(parent) calls parent.append", function() {149 var parent = mockProxy();150 collection.appendTo(parent);151 expect(parent.append).toHaveBeenCalledWith(collection);152 });153 it("children() returns children from all in collection", function() {154 var children = [mockProxy(), mockProxy(), mockProxy(), mockProxy()];155 mocks[0]._children = children.slice(0, 2);156 mocks[2]._children = children.slice(2, 4);157 expect(collection.children().toArray()).toEqual(children);158 });159 it("children() with matcher returns children from all in collection", function() {160 var children = [mockProxy(), mockProxy(), mockProxy(), mockProxy()];161 children[0].type = children[2].type = "Foo";162 mocks[0]._children = children.slice(0, 2);163 mocks[2]._children = children.slice(2, 4);164 expect(collection.children("Foo").toArray()).toEqual([children[0], children[2]]);165 });166 it("find() returns descendants from all proxies in collection", function() {167 var children = [mockProxy(), mockProxy(), mockProxy(), mockProxy()];168 mocks[0]._children = [children[0]];169 mocks[2]._children = [children[1]];170 children[1]._children = children.slice(2, 4);171 expect(collection.find("*").toArray().length).toEqual(children.length);172 expect(collection.find("*").toArray()).toEqual(children);173 });174 it("find() returns no duplicates", function() {175 var children = [mockProxy(), mockProxy(), mockProxy(), mockProxy()];176 mocks[0]._children = [children[0]];177 children[0]._children = [children[1]];178 children[1]._children = [children[2]];179 children[2]._children = [children[3]];180 var result = collection.find("*").find("*");181 expect(result.length).toBe(3);182 expect(result.indexOf(children[1])).not.toBe(-1);183 expect(result.indexOf(children[2])).not.toBe(-1);184 expect(result.indexOf(children[3])).not.toBe(-1);185 });186 });...

Full Screen

Full Screen

proxy-specs.js

Source:proxy-specs.js Github

copy

Full Screen

...31 return proxy;32}33describe('proxy', function () {34 it('should override default params', function () {35 let j = mockProxy({server: '127.0.0.2'});36 j.server.should.equal('127.0.0.2');37 j.port.should.equal(4444);38 });39 it('should save session id on session creation', async function () {40 let j = mockProxy();41 let [res, body] = await j.proxy('/session', 'POST', {desiredCapabilities: {}});42 res.statusCode.should.equal(200);43 body.should.eql({status: 0, sessionId: '123', value: {browserName: 'boo'}});44 j.sessionId.should.equal('123');45 });46 describe('getUrlForProxy', function () {47 it('should modify session id, host, and port', function () {48 let j = mockProxy({sessionId: '123'});49 j.getUrlForProxy('http://host.com:1234/wd/hub/session/456/element/200/value')50 .should.eql('http://localhost:4444/wd/hub/session/123/element/200/value');51 });52 it('should prepend scheme, host and port if not provided', function () {53 let j = mockProxy({sessionId: '123'});54 j.getUrlForProxy('/wd/hub/session/456/element/200/value')55 .should.eql('http://localhost:4444/wd/hub/session/123/element/200/value');56 });57 it('should respect nonstandard incoming request base path', function () {58 let j = mockProxy({sessionId: '123', reqBasePath: ''});59 j.getUrlForProxy('/session/456/element/200/value')60 .should.eql('http://localhost:4444/wd/hub/session/123/element/200/value');61 j = mockProxy({sessionId: '123', reqBasePath: '/my/base/path'});62 j.getUrlForProxy('/my/base/path/session/456/element/200/value')63 .should.eql('http://localhost:4444/wd/hub/session/123/element/200/value');64 });65 it('should work with urls which do not have session ids', function () {66 let j = mockProxy({sessionId: '123'});67 j.getUrlForProxy('http://host.com:1234/wd/hub/session')68 .should.eql('http://localhost:4444/wd/hub/session');69 let newUrl = j.getUrlForProxy('/wd/hub/session');70 newUrl.should.eql('http://localhost:4444/wd/hub/session');71 });72 it('should throw an error if url requires a sessionId but its null', function () {73 let j = mockProxy();74 let e;75 try {76 j.getUrlForProxy('/wd/hub/session/456/element/200/value');77 } catch (err) {78 e = err;79 }80 should.exist(e);81 e.message.should.contain('without session id');82 });83 it('should not throw an error if url does not require a session id and its null', function () {84 let j = mockProxy();85 let newUrl = j.getUrlForProxy('/wd/hub/status');86 should.exist(newUrl);87 });88 });89 describe('straight proxy', function () {90 it('should successfully proxy straight', async function () {91 let j = mockProxy();92 let [res, body] = await j.proxy('/status', 'GET');93 res.statusCode.should.equal(200);94 body.should.eql({status: 0, value: {foo: 'bar'}});95 });96 it('should pass along request errors', function () {97 let j = mockProxy({sessionId: '123'});98 j.proxy('/badurl', 'GET').should.eventually.be.rejectedWith('Could not proxy');99 });100 it('should proxy error responses and codes', async function () {101 let j = mockProxy({sessionId: '123'});102 try {103 await j.proxy('/element/bad/text', 'GET');104 } catch (e) {105 isErrorType(e.getActualError(), errors.ElementNotVisibleError).should.be.true;106 }107 });108 });109 describe('command proxy', function () {110 it('should successfully proxy command', async function () {111 let j = mockProxy();112 let res = await j.command('/status', 'GET');113 res.should.eql({foo: 'bar'});114 });115 it('should pass along request errors', function () {116 let j = mockProxy({sessionId: '123'});117 j.command('/badurl', 'GET').should.eventually.be.rejectedWith('Could not proxy');118 });119 it('should throw when a command fails', async function () {120 let j = mockProxy({sessionId: '123'});121 let e = null;122 try {123 await j.command('/element/bad/text', 'GET');124 } catch (err) {125 e = err;126 }127 should.exist(e);128 e.message.should.contain('Invisible element');129 });130 it('should throw when a command fails with a 200 because the status is not 0', async function () {131 let j = mockProxy({sessionId: '123'});132 let e = null;133 try {134 await j.command('/element/200/text', 'GET');135 } catch (err) {136 e = err;137 }138 should.exist(e);139 e.error.should.eql('element not visible');140 });141 it('should throw when a command fails with a 100', async function () {142 let j = mockProxy({sessionId: '123'});143 let e = null;144 try {145 await j.command('/session/badchrome/nochrome', 'GET');146 } catch (err) {147 e = err;148 }149 should.exist(e);150 e.message.should.contain('chrome not reachable');151 });152 });153 describe('req/res proxy', function () {154 it('should successfully proxy via req and send to res', async function () {155 let j = mockProxy();156 let [req, res] = buildReqRes('/status', 'GET');157 await j.proxyReqRes(req, res);158 res.headers['content-type'].should.equal('application/json; charset=utf-8');159 res.sentCode.should.equal(200);160 res.sentBody.should.eql({status: 0, value: {foo: 'bar'}});161 });162 it('should rewrite the inner session id so it doesnt change', async function () {163 let j = mockProxy({sessionId: '123'});164 let [req, res] = buildReqRes('/element/200/value', 'GET');165 await j.proxyReqRes(req, res);166 res.sentBody.should.eql({status: 0, value: 'foobar', sessionId: '123'});167 });168 it('should rewrite the inner session id with sessionId in url', async function () {169 let j = mockProxy({sessionId: '123'});170 let [req, res] = buildReqRes('/wd/hub/session/456/element/200/value', 'POST');171 await j.proxyReqRes(req, res);172 res.sentBody.should.eql({status: 0, value: 'foobar', sessionId: '456'});173 });174 it('should pass through urls that do not require session IDs', async function () {175 let j = mockProxy({sessionId: '123'});176 let [req, res] = buildReqRes('/wd/hub/status', 'GET');177 await j.proxyReqRes(req, res);178 res.sentBody.should.eql({status: 0, value: {'foo': 'bar'}});179 });180 it('should proxy strange responses', async function () {181 let j = mockProxy({sessionId: '123'});182 let [req, res] = buildReqRes('/nochrome', 'GET');183 await j.proxyReqRes(req, res);184 res.sentCode.should.equal(100);185 res.sentBody.should.eql({status: 0, value: {message: 'chrome not reachable'}});186 });187 });...

Full Screen

Full Screen

heartbeat-generator-test.js

Source:heartbeat-generator-test.js Github

copy

Full Screen

1var test = require('../test');2var HeartbeatGenerator = require(process.cwd() + '/services/heartbeat-generator');3describe('HeartbeatGenerator',function() {4 var BASE_TIME = 1000000000000;5 var redis = null;6 var mockProxy = null;7 beforeEach(function () {8 test.timekeeper.freeze(BASE_TIME);9 test.mockery.enable();10 test.mockery.registerMock('then-redis', test.mockredis);11 test.mockery.warnOnUnregistered(false);12 test.mockredis.reset();13 redis = test.mockredis.createClient();14 mockProxy = {15 config: {imei: '123456789012345',heartbeatInterval: 10 / HeartbeatGenerator.MILLIS_PER_MIN},16 messages: []17 };18 mockProxy.sendPrivate = function(buffer,ignoreAckHint){19 mockProxy.messages.push([buffer.inspect(),ignoreAckHint]);20 };21 mockProxy.snapshot = function(){22 var messages = mockProxy.messages;23 mockProxy.messages = [];24 return messages;25 }26 });27 afterEach(function () {28 test.mockery.deregisterMock('then-redis');29 test.mockery.disable();30 test.mockredis.snapshot().should.eql([]);31 test.pp.snapshot().should.eql([]);32 mockProxy.snapshot().should.eql([]);33 test.timekeeper.reset();34 });35 it('should send a startup but then skip regular heartbeats if recent messages have been sent',function(done){36 test.mockredis.lookup.get['m2m-transmit:last-private-timestamp'] = BASE_TIME;37 test.mockredis.lookup.llen['m2m-transmit:queue'] = 0;38 test.mockredis.lookup.get['m2m-transmit:last-sequence-number'] = '7';39 var events = [];40 var heartbeat = new HeartbeatGenerator(mockProxy);41 heartbeat.on('note',function(type){42 events.push(type);43 if (events.length > 1) {44 heartbeat.stop();45 events.should.eql(['heartbeat','skip']);46 test.pp.snapshot().should.eql([47 '[heartbeat ] start watching',48 '[heartbeat ] send heartbeat: 1',49 '[heartbeat ] stop watching']);50 test.mockredis.snapshot().should.eql([51 {incr: 'm2m-transmit:last-sequence-number'},52 {get: 'm2m-transmit:last-private-timestamp'}]);53 mockProxy.snapshot().should.eql([['<Buffer aa 10 01 00 08 00 00 00 e8 d4 a5 10 00 01 00 02 00 0f 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 11>',8]]);54 done();55 }56 });57 heartbeat.start(mockProxy.config,redis);58 });59 it('should send a startup but then skip regular heartbeats if messages are in the queue',function(done){60 var nextTime = BASE_TIME;61 test.mockredis.lookup.get['m2m-transmit:last-private-timestamp'] = nextTime;62 test.mockredis.lookup.llen['m2m-transmit:queue'] = 1;63 test.mockredis.lookup.get['m2m-transmit:last-sequence-number'] = '7';64 var events = [];65 var heartbeat = new HeartbeatGenerator(mockProxy);66 heartbeat.on('note',function(type){67 events.push(type);68 test.timekeeper.reset();69 test.timekeeper.freeze(nextTime += 20);70 if (events.length > 1) {71 heartbeat.stop();72 events.should.eql(['heartbeat','skip']);73 test.pp.snapshot().should.eql([74 '[heartbeat ] start watching',75 '[heartbeat ] send heartbeat: 1',76 '[heartbeat ] stop watching']);77 test.mockredis.snapshot().should.eql([78 {incr: 'm2m-transmit:last-sequence-number'},79 {get: 'm2m-transmit:last-private-timestamp'},80 {llen: 'm2m-transmit:queue'}81 ]);82 mockProxy.snapshot().should.eql([['<Buffer aa 10 01 00 08 00 00 00 e8 d4 a5 10 00 01 00 02 00 0f 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 11>',8]]);83 done();84 }85 });86 heartbeat.start(mockProxy.config,redis);87 });88 it('should send a startup and then regular heartbeats if no other messages have been sent and the queue is empty',function(done){89 var nextTime = BASE_TIME;90 test.mockredis.lookup.get['m2m-transmit:last-private-timestamp'] = nextTime;91 test.mockredis.lookup.get['m2m-transmit:last-sequence-number'] = '7';92 test.mockredis.lookup.llen['m2m-transmit:queue'] = 0;93 var events = [];94 var heartbeat = new HeartbeatGenerator(mockProxy);95 heartbeat.on('note',function(type){96 events.push(type);97 test.timekeeper.reset();98 test.timekeeper.freeze(nextTime += 20);99 if (events.length > 1) {100 heartbeat.stop();101 events.should.eql(['heartbeat','heartbeat']);102 test.pp.snapshot().should.eql([103 '[heartbeat ] start watching',104 '[heartbeat ] send heartbeat: 1',105 '[heartbeat ] send heartbeat: 0',106 '[heartbeat ] stop watching']);107 test.mockredis.snapshot().should.eql([108 {incr: 'm2m-transmit:last-sequence-number'},109 {get: 'm2m-transmit:last-private-timestamp'},110 {llen: 'm2m-transmit:queue'},111 {incr: 'm2m-transmit:last-sequence-number'}112 ]);113 mockProxy.snapshot().should.eql([114 ['<Buffer aa 10 01 00 08 00 00 00 e8 d4 a5 10 00 01 00 02 00 0f 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 11>',8],115 ['<Buffer aa 10 00 00 09 00 00 00 e8 d4 a5 10 14 01 00 02 00 0f 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 18>',9]116 ]);117 done();118 }119 });120 heartbeat.start(mockProxy.config,redis);121 });122 it('should throw an error if start called twice',function(done){123 test.mockredis.lookup.get['m2m-transmit:last-sequence-number'] = '7';124 var heartbeat = new HeartbeatGenerator(mockProxy).start(mockProxy.config,redis);125 test.expect(function(){ heartbeat.start(mockProxy.config,redis); }).to.throw('already started');126 heartbeat.stop();127 test.pp.snapshot().should.eql([128 '[heartbeat ] start watching',129 '[heartbeat ] send heartbeat: 1',130 '[heartbeat ] stop watching']);131 test.mockredis.snapshot().should.eql([132 {incr: 'm2m-transmit:last-sequence-number'}133 ]);134 mockProxy.snapshot().should.eql([['<Buffer aa 10 01 00 08 00 00 00 e8 d4 a5 10 00 01 00 02 00 0f 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 11>',8]]);135 done();136 });137 it('should throw an error if stopped before started',function(done){138 var heartbeat = new HeartbeatGenerator(mockProxy);139 test.expect(function(){ heartbeat.stop(); }).to.throw('not started');140 test.pp.snapshot().should.eql([]);141 test.mockredis.snapshot().should.eql([]);142 done();143 });...

Full Screen

Full Screen

StandaloneMockProxy.js

Source:StandaloneMockProxy.js Github

copy

Full Screen

1const veUtil = require('./lib/veUtil');2const config = require('./lib/config');3// create proxy server4const MockProxy = require('./lib/mockProxy');5const mockProxy = new MockProxy();6let VISITOR_SESSION_ID;7const genesysResponses = require('./lib/genesys');8const PROXY_SERVER_PORT = 9001;9const SOCKET_SERVER_PORT = 9898;10const genesysPageLocation = config.test_env.baseURL + '/static/genesys.purecloud.html';11const accessToken = veUtil.getUUID();12const channelId = veUtil.getUUID();13genesysResponses.userResponse.organization.id = config.test_env.organizationId;14genesysResponses.channels.connectUri = `ws://localhost:${SOCKET_SERVER_PORT}/`;15genesysResponses.channels.id = channelId;16genesysResponses.getChannels.entities[0].connectUri = `ws://localhost:${SOCKET_SERVER_PORT}/`;17genesysResponses.getChannels.entities[0].id = channelId;18genesysResponses.messages.entities[0].body = JSON.stringify({ interactionId: VISITOR_SESSION_ID });19const authURLParams = veUtil.generateUrlParamters({20 response_type: 'token',21 client_id: config.test_env.clientId,22 redirect_uri: encodeURIComponent(genesysPageLocation)23});24const authHeader = {25 location: genesysPageLocation + '#access_token=' + accessToken + '&expires_in=86399&token_type=bearer'26};27// mandatory28mockProxy.mockIt({ path: '/oauth/(.*)', method: 'GET' }, null, 302, authHeader);29mockProxy.mockIt({ path: '/api/v2/users/me\\?expand=conversationSummary', method: 'GET' }, genesysResponses.conversationSummary);30mockProxy.mockIt({ path: '/api/v2/users/me\\?expand=organization', method: 'GET' }, genesysResponses.userResponse);31mockProxy.mockIt({ path: '/api/v2/users/:userId/presences/PURECLOUD', method: 'PATCH' }, genesysResponses.purecloud);32mockProxy.mockIt({ path: '/api/v2/notifications/channels', method: 'POST' }, genesysResponses.channels);33mockProxy.mockIt({ path: '/api/v2/notifications/channels', method: 'GET' }, genesysResponses.getChannels);34mockProxy.mockIt({ path: '/api/v2/conversations/chats', method: 'GET' }, genesysResponses.chats[0]);35mockProxy.mockIt({ path: '/api/v2/notifications/channels/' + channelId + '/subscriptions', method: 'GET' }, genesysResponses.subscriptions[0]);36mockProxy.mockIt({ path: '/api/v2/notifications/channels/' + channelId + '/subscriptions', method: 'PUT' }, genesysResponses.subscriptions[0]);37// web hook38mockProxy.mockIt({ path: '/api/v2/conversations', method: 'GET' }, genesysResponses.conversations[0]);39// not mandaroty40/*41mockProxy.mockIt({ path: '/api/v2/users/me\\?expand=chats', method: 'GET' }, genesysResponses.chats[0]);42*/43// not used in this tests44/*45mockProxy.mockIt({ path: '/AGENT_PARTICIPANT_ID', method: 'GET' }, genesysResponses.participants);46mockProxy.mockIt({ path: '/CONVERSATION_ID', method: 'GET' }, genesysResponses.conversationChat);47*/48// start 80 port proxy server49mockProxy.startHttpProxyServer(PROXY_SERVER_PORT);50// start 443 port proxy server51mockProxy.startSSlProxyServer(PROXY_SERVER_PORT);52// start https server for mock responses53mockProxy.startHttpServer(PROXY_SERVER_PORT);54// start socket server for mock socket connection...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const { AppiumBaseDriver } = require('appium-base-driver');3const { startServer } = require('appium');4const { serverArgs } = require('appium/build/lib/parser');5const { iosDriverArgs } = require('appium-ios-driver');6const { androidDriverArgs } = require('appium-android-driver');7const { serverDefaults } = require('appium/build/lib/server-utils');8const server = serverArgs(serverDefaults);9const ios = iosDriverArgs();10const android = androidDriverArgs();11const args = Object.assign({}, server, ios, android);12const driver = new AppiumBaseDriver(args);13startServer(args, async (err, appium) => {14 if (err) {15 console.error(err);16 return;17 }18 const driver = appium.driver;19 const proxy = await driver.mockProxy();20 const mock = proxy.mock;21 const url = proxy.url;22 .withUrl(url)23 .withMethod('GET')24 .withResponse({25 content: {26 }27 });28 const client = wd.promiseChainRemote({29 });30 await client.init({

Full Screen

Using AI Code Generation

copy

Full Screen

1const { BaseDriver } = require('appium-base-driver');2const { mockProxy } = require('appium-base-driver').test;3const driver = new BaseDriver();4const proxy = mockProxy(driver, BaseDriver, [5]);6proxy.createSession('foo', 'bar', 'baz');7proxy.deleteSession();8proxy.executeCommand();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { BaseDriver } = require('appium-base-driver');2const { myMock } = require('./myMock');3const { myMockProxy } = require('./myMockProxy');4class TestDriver extends BaseDriver {5 constructor () {6 super();7 this.proxyMethods = ['myMock'];8 }9 async myMock () {10 return await myMock();11 }12}13const testDriver = new TestDriver();14testDriver.myMockProxy = myMockProxy;15testDriver.myMockProxy();16async function myMock () {17 return 'myMock';18}19module.exports = { myMock };20const { myMock } = require('./myMock');21async function myMockProxy () {22 const myMockResult = await myMock();23 console.log(myMockResult);24}25module.exports = { myMockProxy };

Full Screen

Using AI Code Generation

copy

Full Screen

1 log: function() {2 console.log(arguments);3 }4}, function(err, proxy) {5 if (err) {6 console.log("Error in creating proxy", err);7 } else {8 console.log("Proxy created successfully");9 }10});11 log: function() {12 console.log(arguments);13 }14}, function(err, proxy) {15 if (err) {16 console.log("Error in creating proxy", err);17 } else {18 console.log("Proxy created successfully");19 }20});

Full Screen

Using AI Code Generation

copy

Full Screen

1let BaseDriver = require('appium-base-driver');2let AppiumDriver = require('./appium/appium_driver.js');3let appiumDriver = new AppiumDriver();4appiumDriver.mockProxy('findElement', function (strategy, selector) {5 return new BaseDriver.WebElement('mock_element_id');6});7let BaseDriver = require('appium-base-driver');8let appiumDriver = new BaseDriver();9appiumDriver.mockProxy('findElement', function (strategy, selector) {10 return new BaseDriver.WebElement('mock_element_id');11});12let BaseDriver = require('appium-base-driver');13let appiumDriver = new BaseDriver();14appiumDriver.mockProxy('findElement', function (strategy, selector) {15 return new BaseDriver.WebElement('mock_element_id');16});

Full Screen

Using AI Code Generation

copy

Full Screen

1const AppiumBaseDriver = require('appium-base-driver');2const MockProxy = AppiumBaseDriver.mockProxy;3const server = appium.main();4server.close();5const { server, routeConfiguringFunction } = require('./lib/appium');6const appium = module.exports = { main };7async function main () {8 return server;9}

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Base Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful