Best JavaScript code snippet using appium
syntax-mediakeysession.js
Source:syntax-mediakeysession.js
1function runTest(config) {2 var keysystem = config.keysystem;3 var testname = testnamePrefix(null, config.keysystem);4 var initDataType = config.initDataType;5 var initData = config.initData;6 var configuration = {7 initDataTypes: [config.initDataType],8 audioCapabilities: [{contentType: config.audioType}],9 videoCapabilities: [{contentType: config.videoType}],10 sessionTypes: ['temporary']11 };12 var kTypeSpecificGenerateRequestExceptionsTestCases = [13 // Tests in this set use a shortened parameter name due to14 // format_value() only returning the first 60 characters as the15 // result. With a longer name the first 60 characters is not16 // enough to determine which test failed. Even with the17 // shortened name, the error message for the last couple of18 // tests is the same.19 // Too few parameters.20 {21 exception: 'TypeError',22 func: function (mk1, type) {23 return mk1.createSession().generateRequest(type);24 }25 },26 // Invalid parameters.27 {28 exception: 'TypeError',29 func: function (mk2, type) {30 return mk2.createSession().generateRequest(type, '');31 }32 },33 {34 exception: 'TypeError',35 func: function (mk3, type) {36 return mk3.createSession().generateRequest(type, null);37 }38 },39 {40 exception: 'TypeError',41 func: function (mk4, type) {42 return mk4.createSession().generateRequest(type, undefined);43 }44 },45 {46 exception: 'TypeError',47 func: function (mk5, type) {48 return mk5.createSession().generateRequest(type, 1);49 }50 },51 // (new Uint8Array(0)) returns empty array. So 'TypeError' should52 // be returned.53 {54 exception: 'TypeError',55 func: function (mk6, type) {56 return mk6.createSession().generateRequest(type, new Uint8Array(0));57 }58 }59 ];60 function generateRequestTestExceptions(){61 return new Promise(function(resolve, reject){62 isInitDataTypeSupported(keysystem, initDataType).then(function (isTypeSupported) {63 assert_true(isTypeSupported, "initDataType not supported");64 return navigator.requestMediaKeySystemAccess(keysystem, [configuration]);65 }).then(function (access) {66 return access.createMediaKeys();67 }).then(function (mediaKeys) {68 var mp4SessionPromises = kTypeSpecificGenerateRequestExceptionsTestCases.map(function (testCase) {69 return test_exception(testCase, mediaKeys, initDataType, initData);70 });71 assert_not_equals(mp4SessionPromises.length, 0);72 return Promise.all(mp4SessionPromises);73 }).then(function (result) {74 resolve();75 }).catch(function (error) {76 reject(error);77 });78 })79 }80 promise_test(function() {81 return generateRequestTestExceptions();82 }, testname + ' test MediaKeySession generateRequest() exceptions.');83 var kLoadExceptionsTestCases = [84 // Too few parameters.85 {86 exception: 'TypeError',87 func: function (mk1) {88 return mk1.createSession('temporary').load();89 }90 },91 {92 exception: 'TypeError',93 func: function (mk3) {94 return mk3.createSession('temporary').load('');95 }96 },97 {98 exception: 'TypeError',99 func: function (mk4) {100 return mk4.createSession('temporary').load(1);101 }102 },103 {104 exception: 'TypeError',105 func: function (mk5) {106 return mk5.createSession('temporary').load('!@#$%^&*()');107 }108 },109 {110 exception: 'TypeError',111 func: function (mk6) {112 return mk6.createSession('temporary').load('1234');113 }114 }115 ];116 function loadTestExceptions(){117 return new Promise(function(resolve, reject){118 isInitDataTypeSupported(keysystem, initDataType).then(function (isTypeSupported) {119 assert_true(isTypeSupported, "initDataType not supported");120 return navigator.requestMediaKeySystemAccess(keysystem, [configuration]);121 }).then(function (access) {122 return access.createMediaKeys();123 }).then(function (mediaKeys) {124 var sessionPromises = kLoadExceptionsTestCases.map(function (testCase) {125 return test_exception(testCase, mediaKeys);126 });127 assert_not_equals(sessionPromises.length, 0);128 return Promise.all(sessionPromises);129 }).then(function () {130 resolve();131 }).catch(function (error) {132 reject(error);133 });134 })135 }136 promise_test(function() {137 return loadTestExceptions();138 }, testname + ' test MediaKeySession load() exceptions.');139 // All calls to |func| in this group are supposed to succeed.140 // However, the spec notes that some things are optional for141 // Clear Key. In particular, support for persistent sessions142 // is optional. Since some implementations won't support some143 // features, a NotSupportedError is treated as a success144 // if |isNotSupportedAllowed| is true.145 var kCreateSessionTestCases = [146 // Use the default sessionType.147 {148 func: function(mk) { return mk.createSession(); },149 isNotSupportedAllowed: false150 },151 // Try variations of sessionType.152 {153 func: function(mk) { return mk.createSession('temporary'); },154 isNotSupportedAllowed: false155 },156 {157 func: function(mk) { return mk.createSession(undefined); },158 isNotSupportedAllowed: false159 },160 {161 // Since this is optional, some Clear Key implementations162 // will succeed, others will return a "NotSupportedError".163 // Both are allowed results.164 func: function(mk) { return mk.createSession('persistent-license'); },165 isNotSupportedAllowed: true166 },167 // Try additional parameter, which should be ignored.168 {169 func: function(mk) { return mk.createSession('temporary', 'extra'); },170 isNotSupportedAllowed: false171 }172 ];173 // This function checks that calling generateRequest() works for174 // various sessions. |testCase.func| creates a MediaKeySession175 // object, and then generateRequest() is called on that object. It176 // allows for an NotSupportedError to be generated and treated as a177 // success, if allowed. See comment above kCreateSessionTestCases.178 function test_generateRequest(testCase, mediaKeys, type, initData) {179 var mediaKeySession;180 try {181 mediaKeySession = testCase.func.call(null, mediaKeys);182 } catch (e) {183 assert_true(testCase.isNotSupportedAllowed);184 assert_equals(e.name, 'NotSupportedError');185 return Promise.resolve('not supported');186 }187 return mediaKeySession.generateRequest(type, initData);188 }189 function generateRequestForVariousSessions(){190 return new Promise(function(resolve, reject){191 isInitDataTypeSupported(keysystem, initDataType).then(function (isTypeSupported) {192 assert_true(isTypeSupported, "initDataType should be supported");193 return navigator.requestMediaKeySystemAccess(keysystem, [configuration]);194 }).then(function (access) {195 return access.createMediaKeys();196 }).then(function (mediaKeys) {197 var mp4SessionPromises = kCreateSessionTestCases.map(function (testCase) {198 return test_generateRequest(testCase, mediaKeys, initDataType, initData);199 });200 assert_not_equals(mp4SessionPromises.length, 0);201 return Promise.all(mp4SessionPromises);202 }).then(function () {203 resolve();204 }).catch(function (error) {205 reject(error);206 });207 })208 }209 promise_test(function() {210 return generateRequestForVariousSessions();211 }, testname + ' test if MediaKeySession generateRequest() resolves for various sessions');212 var kUpdateSessionExceptionsTestCases = [213 // Tests in this set use a shortened parameter name due to214 // format_value() only returning the first 60 characters as the215 // result. With a longer name (mediaKeySession) the first 60216 // characters is not enough to determine which test failed.217 // Too few parameters.218 {219 exception: 'TypeError',220 func: function (s) {221 return s.update();222 }223 },224 // Invalid parameters.225 {226 exception: 'TypeError',227 func: function (s) {228 return s.update('');229 }230 },231 {232 exception: 'TypeError',233 func: function (s) {234 return s.update(null);235 }236 },237 {238 exception: 'TypeError',239 func: function (s) {240 return s.update(undefined);241 }242 },243 {244 exception: 'TypeError',245 func: function (s) {246 return s.update(1);247 }248 },249 // (new Uint8Array(0)) returns empty array. So 'TypeError' should250 // be returned.251 {252 exception: 'TypeError',253 func: function (s) {254 return s.update(new Uint8Array(0));255 }256 }257 ];258 function updateTestExceptions(){259 return new Promise(function(resolve, reject){260 isInitDataTypeSupported(keysystem, initDataType).then(function (isTypeSupported) {261 assert_true(isTypeSupported, "initDataType not supported");262 return navigator.requestMediaKeySystemAccess(keysystem, [configuration]);263 }).then(function (access) {264 return access.createMediaKeys();265 }).then(function (mediaKeys) {266 var mp4SessionPromises = kUpdateSessionExceptionsTestCases.map(function (testCase) {267 var mediaKeySession = mediaKeys.createSession();268 return mediaKeySession.generateRequest(initDataType, initData).then(function (result) {269 return test_exception(testCase, mediaKeySession);270 });271 });272 assert_not_equals(mp4SessionPromises.length, 0);273 return Promise.all(mp4SessionPromises);274 }).then(function () {275 resolve();276 }).catch(function (error) {277 reject(error);278 });279 })280 }281 promise_test(function() {282 return updateTestExceptions();283 }, testname + ' test MediaKeySession update() exceptions.');284 function create_close_exception_test(mediaKeys) {285 var mediaKeySession = mediaKeys.createSession();286 return mediaKeySession.close().then(function (result) {287 assert_unreached('close() should not succeed if session uninitialized');288 }).catch(function (error) {289 assert_equals(error.name, 'InvalidStateError');290 // Return something so the promise resolves.291 return Promise.resolve();292 });293 }294 function closeTestExceptions(){295 return new Promise(function(resolve, reject){296 isInitDataTypeSupported(keysystem, initDataType).then(function (isTypeSupported) {297 assert_true(isTypeSupported, "initDataType not supported");298 return navigator.requestMediaKeySystemAccess(keysystem, [configuration]);299 }).then(function (access) {300 return access.createMediaKeys();301 }).then(function (mediaKeys) {302 return create_close_exception_test(mediaKeys);303 }).then(function () {304 resolve();305 }).catch(function (error) {306 reject(error);307 });308 });309 }310 promise_test(function() {311 return closeTestExceptions();312 }, testname + ' test MediaKeySession close() exceptions.');313 function create_remove_exception_test(mediaKeys, type, initData) {314 // remove() on an uninitialized session should fail.315 var mediaKeySession = mediaKeys.createSession('temporary');316 return mediaKeySession.remove().then(function (result) {317 assert_unreached('remove() should not succeed if session uninitialized');318 }, function (error) {319 assert_equals(error.name, 'InvalidStateError');320 });321 }322 function removeTestException(){323 return new Promise(function(resolve, reject){324 isInitDataTypeSupported(keysystem, initDataType).then(function (isTypeSupported) {325 assert_true(isTypeSupported, "initDataType not supported");326 return navigator.requestMediaKeySystemAccess(keysystem, [configuration]);327 }).then(function (access) {328 return access.createMediaKeys();329 }).then(function (mediaKeys) {330 return create_remove_exception_test(mediaKeys, initDataType, initData);331 }).then(function () {332 resolve();333 }).catch(function (error) {334 reject(error);335 });336 });337 }338 promise_test(function() {339 return removeTestException();340 }, testname + ' test MediaKeySession remove() exceptions.');341 // All calls to |func| in this group are supposed to succeed.342 // However, the spec notes that some things are optional for343 // Clear Key. In particular, support for persistent sessions344 // is optional. Since some implementations won't support some345 // features, a NotSupportedError is treated as a success346 // if |isNotSupportedAllowed| is true.347 var kCreateSessionTestCases = [348 // Use the default sessionType.349 {350 func: function (mk) {351 return mk.createSession();352 },353 isNotSupportedAllowed: false354 },355 // Try variations of sessionType.356 {357 func: function (mk) {358 return mk.createSession('temporary');359 },360 isNotSupportedAllowed: false361 },362 {363 func: function (mk) {364 return mk.createSession(undefined);365 },366 isNotSupportedAllowed: false367 },368 {369 // Since this is optional, some Clear Key implementations370 // will succeed, others will return a "NotSupportedError".371 // Both are allowed results.372 func: function (mk) {373 return mk.createSession('persistent-license');374 },375 isNotSupportedAllowed: true376 },377 // Try additional parameter, which should be ignored.378 {379 func: function (mk) {380 return mk.createSession('temporary', 'extra');381 },382 isNotSupportedAllowed: false383 }384 ];385 // This function checks that calling |testCase.func| creates a386 // MediaKeySession object with some default values. It also387 // allows for an NotSupportedError to be generated and treated as a388 // success, if allowed. See comment above kCreateSessionTestCases.389 function test_createSession(testCase, mediaKeys) {390 var mediaKeySession;391 try {392 mediaKeySession = testCase.func.call(null, mediaKeys);393 } catch (e) {394 assert_true(testCase.isNotSupportedAllowed);395 return;396 }397 assert_equals(typeof mediaKeySession, 'object');398 assert_equals(typeof mediaKeySession.addEventListener, 'function');399 assert_equals(typeof mediaKeySession.sessionId, 'string');400 assert_equals(typeof mediaKeySession.expiration, 'number');401 assert_equals(typeof mediaKeySession.closed, 'object');402 assert_equals(typeof mediaKeySession.keyStatuses, 'object');403 assert_equals(typeof mediaKeySession.onkeystatuseschange, 'object');404 assert_equals(typeof mediaKeySession.onmessage, 'object');405 assert_equals(typeof mediaKeySession.generateRequest, 'function');406 assert_equals(typeof mediaKeySession.load, 'function');407 assert_equals(typeof mediaKeySession.update, 'function');408 assert_equals(typeof mediaKeySession.close, 'function');409 assert_equals(typeof mediaKeySession.remove, 'function');410 assert_equals(mediaKeySession.sessionId, '');411 }412 function createSessionTest(){413 return new Promise(function(resolve, reject){414 isInitDataTypeSupported(keysystem, initDataType).then(function (isTypeSupported) {415 assert_true(isTypeSupported, "initDataType not supported");416 return navigator.requestMediaKeySystemAccess(keysystem, [configuration]);417 }).then(function (access) {418 return access.createMediaKeys();419 }).then(function (mediaKeys) {420 kCreateSessionTestCases.map(function (testCase) {421 test_createSession(testCase, mediaKeys);422 });423 resolve();424 }).catch(function (error) {425 reject(error);426 });427 })428 }429 promise_test(function() {430 return createSessionTest();431 }, testname + ' test MediaKeySession attribute syntax.');...
driver-specs.js
Source:driver-specs.js
1// transpile:mocha2import { AppiumDriver } from '../lib/appium';3import { FakeDriver } from 'appium-fake-driver';4import { BASE_CAPS, W3C_CAPS } from './helpers';5import _ from 'lodash';6import sinon from 'sinon';7import chai from 'chai';8import chaiAsPromised from 'chai-as-promised';9import { XCUITestDriver } from 'appium-xcuitest-driver';10import { IosDriver } from 'appium-ios-driver';11import { AndroidUiautomator2Driver } from 'appium-uiautomator2-driver';12import { sleep } from 'asyncbox';13import { insertAppiumPrefixes } from '../lib/utils';14chai.should();15chai.use(chaiAsPromised);16const SESSION_ID = 1;17describe('AppiumDriver', function () {18 describe('AppiumDriver', function () {19 function getDriverAndFakeDriver () {20 const appium = new AppiumDriver({});21 const fakeDriver = new FakeDriver();22 const mockFakeDriver = sinon.mock(fakeDriver);23 appium.getDriverAndVersionForCaps = function (/*args*/) {24 return {25 driver: function Driver () {26 return fakeDriver;27 },28 version: '1.2.3',29 };30 };31 return [appium, mockFakeDriver];32 }33 describe('createSession', function () {34 let appium;35 let mockFakeDriver;36 beforeEach(function () {37 [appium, mockFakeDriver] = getDriverAndFakeDriver();38 });39 afterEach(async function () {40 mockFakeDriver.restore();41 await appium.deleteSession(SESSION_ID);42 });43 it(`should call inner driver's createSession with desired capabilities`, async function () {44 mockFakeDriver.expects('createSession')45 .once().withExactArgs(BASE_CAPS, undefined, null, [])46 .returns([SESSION_ID, BASE_CAPS]);47 await appium.createSession(BASE_CAPS);48 mockFakeDriver.verify();49 });50 it(`should call inner driver's createSession with desired and default capabilities`, async function () {51 let defaultCaps = {deviceName: 'Emulator'};52 let allCaps = _.extend(_.clone(defaultCaps), BASE_CAPS);53 appium.args.defaultCapabilities = defaultCaps;54 mockFakeDriver.expects('createSession')55 .once().withArgs(allCaps)56 .returns([SESSION_ID, allCaps]);57 await appium.createSession(BASE_CAPS);58 mockFakeDriver.verify();59 });60 it(`should call inner driver's createSession with desired and default capabilities without overriding caps`, async function () {61 // a default capability with the same key as a desired capability62 // should do nothing63 let defaultCaps = {platformName: 'Ersatz'};64 appium.args.defaultCapabilities = defaultCaps;65 mockFakeDriver.expects('createSession')66 .once().withArgs(BASE_CAPS)67 .returns([SESSION_ID, BASE_CAPS]);68 await appium.createSession(BASE_CAPS);69 mockFakeDriver.verify();70 });71 it('should kill all other sessions if sessionOverride is on', async function () {72 appium.args.sessionOverride = true;73 // mock three sessions that should be removed when the new one is created74 let fakeDrivers = [75 new FakeDriver(),76 new FakeDriver(),77 new FakeDriver(),78 ];79 let mockFakeDrivers = _.map(fakeDrivers, (fd) => sinon.mock(fd));80 mockFakeDrivers[0].expects('deleteSession')81 .once();82 mockFakeDrivers[1].expects('deleteSession')83 .once()84 .throws('Cannot shut down Android driver; it has already shut down');85 mockFakeDrivers[2].expects('deleteSession')86 .once();87 appium.sessions['abc-123-xyz'] = fakeDrivers[0];88 appium.sessions['xyz-321-abc'] = fakeDrivers[1];89 appium.sessions['123-abc-xyz'] = fakeDrivers[2];90 let sessions = await appium.getSessions();91 sessions.should.have.length(3);92 mockFakeDriver.expects('createSession')93 .once().withExactArgs(BASE_CAPS, undefined, null, [])94 .returns([SESSION_ID, BASE_CAPS]);95 await appium.createSession(BASE_CAPS);96 sessions = await appium.getSessions();97 sessions.should.have.length(1);98 for (let mfd of mockFakeDrivers) {99 mfd.verify();100 }101 mockFakeDriver.verify();102 });103 it('should call "createSession" with W3C capabilities argument, if provided', async function () {104 mockFakeDriver.expects('createSession')105 .once().withArgs(null, undefined, W3C_CAPS)106 .returns([SESSION_ID, BASE_CAPS]);107 await appium.createSession(undefined, undefined, W3C_CAPS);108 mockFakeDriver.verify();109 });110 it('should call "createSession" with W3C capabilities argument with additional provided parameters', async function () {111 let w3cCaps = {112 ...W3C_CAPS,113 alwaysMatch: {114 ...W3C_CAPS.alwaysMatch,115 'appium:someOtherParm': 'someOtherParm',116 },117 };118 mockFakeDriver.expects('createSession')119 .once().withArgs(null, undefined, {120 alwaysMatch: {121 ...w3cCaps.alwaysMatch,122 'appium:someOtherParm': 'someOtherParm',123 },124 firstMatch: [{}],125 })126 .returns([SESSION_ID, insertAppiumPrefixes(BASE_CAPS)]);127 await appium.createSession(undefined, undefined, w3cCaps);128 mockFakeDriver.verify();129 });130 it('should call "createSession" with JSONWP capabilities if W3C has incomplete capabilities', async function () {131 let w3cCaps = {132 ...W3C_CAPS,133 alwaysMatch: {134 ...W3C_CAPS.alwaysMatch,135 'appium:someOtherParm': 'someOtherParm',136 },137 };138 let jsonwpCaps = {139 ...BASE_CAPS,140 automationName: 'Fake',141 someOtherParam: 'someOtherParam',142 };143 let expectedW3cCaps = {144 ...w3cCaps,145 alwaysMatch: {146 ...w3cCaps.alwaysMatch,147 'appium:automationName': 'Fake',148 'appium:someOtherParam': 'someOtherParam',149 },150 };151 mockFakeDriver.expects('createSession')152 .once().withArgs(jsonwpCaps, undefined, expectedW3cCaps)153 .returns([SESSION_ID, jsonwpCaps]);154 await appium.createSession(jsonwpCaps, undefined, w3cCaps);155 mockFakeDriver.verify();156 });157 });158 describe('deleteSession', function () {159 let appium;160 let mockFakeDriver;161 beforeEach(function () {162 [appium, mockFakeDriver] = getDriverAndFakeDriver();163 });164 afterEach(function () {165 mockFakeDriver.restore();166 });167 it('should remove the session if it is found', async function () {168 let [sessionId] = (await appium.createSession(BASE_CAPS)).value;169 let sessions = await appium.getSessions();170 sessions.should.have.length(1);171 await appium.deleteSession(sessionId);172 sessions = await appium.getSessions();173 sessions.should.have.length(0);174 });175 it('should call inner driver\'s deleteSession method', async function () {176 const [sessionId] = (await appium.createSession(BASE_CAPS)).value;177 mockFakeDriver.expects('deleteSession')178 .once().withExactArgs(sessionId, [])179 .returns();180 await appium.deleteSession(sessionId);181 mockFakeDriver.verify();182 // cleanup, since we faked the delete session call183 await mockFakeDriver.object.deleteSession();184 });185 });186 describe('getSessions', function () {187 let appium;188 let sessions;189 before(function () {190 appium = new AppiumDriver({});191 });192 afterEach(async function () {193 for (let session of sessions) {194 await appium.deleteSession(session.id);195 }196 });197 it('should return an empty array of sessions', async function () {198 sessions = await appium.getSessions();199 sessions.should.be.an('array');200 sessions.should.be.empty;201 });202 it('should return sessions created', async function () {203 let session1 = (await appium.createSession(_.extend(_.clone(BASE_CAPS), {cap: 'value'}))).value;204 let session2 = (await appium.createSession(_.extend(_.clone(BASE_CAPS), {cap: 'other value'}))).value;205 sessions = await appium.getSessions();206 sessions.should.be.an('array');207 sessions.should.have.length(2);208 sessions[0].id.should.equal(session1[0]);209 sessions[0].capabilities.should.eql(session1[1]);210 sessions[1].id.should.equal(session2[0]);211 sessions[1].capabilities.should.eql(session2[1]);212 });213 });214 describe('getStatus', function () {215 let appium;216 before(function () {217 appium = new AppiumDriver({});218 });219 it('should return a status', async function () {220 let status = await appium.getStatus();221 status.build.should.exist;222 status.build.version.should.exist;223 });224 });225 describe('sessionExists', function () {226 });227 describe('attachUnexpectedShutdownHandler', function () {228 let appium;229 let mockFakeDriver;230 beforeEach(function () {231 [appium, mockFakeDriver] = getDriverAndFakeDriver();232 });233 afterEach(async function () {234 await mockFakeDriver.object.deleteSession();235 mockFakeDriver.restore();236 appium.args.defaultCapabilities = {};237 });238 it('should remove session if inner driver unexpectedly exits with an error', async function () {239 let [sessionId,] = (await appium.createSession(_.clone(BASE_CAPS))).value; // eslint-disable-line comma-spacing240 _.keys(appium.sessions).should.contain(sessionId);241 appium.sessions[sessionId].eventEmitter.emit('onUnexpectedShutdown', new Error('Oops'));242 // let event loop spin so rejection is handled243 await sleep(1);244 _.keys(appium.sessions).should.not.contain(sessionId);245 });246 it('should remove session if inner driver unexpectedly exits with no error', async function () {247 let [sessionId,] = (await appium.createSession(_.clone(BASE_CAPS))).value; // eslint-disable-line comma-spacing248 _.keys(appium.sessions).should.contain(sessionId);249 appium.sessions[sessionId].eventEmitter.emit('onUnexpectedShutdown');250 // let event loop spin so rejection is handled251 await sleep(1);252 _.keys(appium.sessions).should.not.contain(sessionId);253 });254 });255 describe('getDriverAndVersionForCaps', function () {256 it('should not blow up if user does not provide platformName', function () {257 const appium = new AppiumDriver({});258 (() => { appium.getDriverAndVersionForCaps({}); }).should.throw(/platformName/);259 });260 it('should ignore automationName Appium', function () {261 const appium = new AppiumDriver({});262 const {driver} = appium.getDriverAndVersionForCaps({263 platformName: 'Android',264 automationName: 'Appium'265 });266 driver.should.be.an.instanceof(Function);267 driver.should.equal(AndroidUiautomator2Driver);268 });269 it('should get XCUITestDriver driver for automationName of XCUITest', function () {270 const appium = new AppiumDriver({});271 const {driver} = appium.getDriverAndVersionForCaps({272 platformName: 'iOS',273 automationName: 'XCUITest'274 });275 driver.should.be.an.instanceof(Function);276 driver.should.equal(XCUITestDriver);277 });278 it('should get iosdriver for ios < 10', function () {279 const appium = new AppiumDriver({});280 const caps = {281 platformName: 'iOS',282 platformVersion: '8.0',283 };284 let {driver} = appium.getDriverAndVersionForCaps(caps);285 driver.should.be.an.instanceof(Function);286 driver.should.equal(IosDriver);287 caps.platformVersion = '8.1';288 ({driver} = appium.getDriverAndVersionForCaps(caps));289 driver.should.equal(IosDriver);290 caps.platformVersion = '9.4';291 ({driver} = appium.getDriverAndVersionForCaps(caps));292 driver.should.equal(IosDriver);293 caps.platformVersion = '';294 ({driver} = appium.getDriverAndVersionForCaps(caps));295 driver.should.equal(IosDriver);296 caps.platformVersion = 'foo';297 ({driver} = appium.getDriverAndVersionForCaps(caps));298 driver.should.equal(IosDriver);299 delete caps.platformVersion;300 ({driver} = appium.getDriverAndVersionForCaps(caps));301 driver.should.equal(IosDriver);302 });303 it('should get xcuitestdriver for ios >= 10', function () {304 const appium = new AppiumDriver({});305 const caps = {306 platformName: 'iOS',307 platformVersion: '10',308 };309 let {driver} = appium.getDriverAndVersionForCaps(caps);310 driver.should.be.an.instanceof(Function);311 driver.should.equal(XCUITestDriver);312 caps.platformVersion = '10.0';313 ({driver} = appium.getDriverAndVersionForCaps(caps));314 driver.should.equal(XCUITestDriver);315 caps.platformVersion = '10.1';316 ({driver} = appium.getDriverAndVersionForCaps(caps));317 driver.should.equal(XCUITestDriver);318 caps.platformVersion = '12.14';319 ({driver} = appium.getDriverAndVersionForCaps(caps));320 driver.should.equal(XCUITestDriver);321 });322 it('should be able to handle different cases in automationName', function () {323 const appium = new AppiumDriver({});324 const caps = {325 platformName: 'iOS',326 platformVersion: '10',327 automationName: 'XcUiTeSt',328 };329 let {driver} = appium.getDriverAndVersionForCaps(caps);330 driver.should.be.an.instanceof(Function);331 driver.should.equal(XCUITestDriver);332 });333 it('should be able to handle different case in platformName', function () {334 const appium = new AppiumDriver({});335 const caps = {336 platformName: 'IoS',337 platformVersion: '10',338 };339 let {driver} = appium.getDriverAndVersionForCaps(caps);340 driver.should.be.an.instanceof(Function);341 driver.should.equal(XCUITestDriver);342 });343 });344 });...
history_synced_tabs_test.js
Source:history_synced_tabs_test.js
1// Copyright 2016 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4import {BrowserService, ensureLazyLoaded} from 'chrome://history/history.js';5import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';6import {TestBrowserService} from 'chrome://test/history/test_browser_service.js';7import {createSession, createWindow, polymerSelectAll} from 'chrome://test/history/test_util.js';8import {flushTasks, waitBeforeNextRender} from 'chrome://test/test_util.m.js';9function getCards(manager) {10 return polymerSelectAll(manager, 'history-synced-device-card');11}12function numWindowSeparators(card) {13 return polymerSelectAll(card, ':not([hidden]).window-separator').length;14}15function assertNoSyncedTabsMessageShown(manager, stringID) {16 assertFalse(manager.$['no-synced-tabs'].hidden);17 const message = loadTimeData.getString(stringID);18 assertNotEquals(-1, manager.$['no-synced-tabs'].textContent.indexOf(message));19}20suite('<history-synced-device-manager>', function() {21 let element;22 let testService;23 const setForeignSessions = function(sessions) {24 element.sessionList = sessions;25 };26 setup(function() {27 document.body.innerHTML = '';28 window.history.replaceState({}, '', '/');29 testService = new TestBrowserService();30 BrowserService.instance_ = testService;31 // Need to ensure lazy_load.html has been imported so that the device32 // manager custom element is defined.33 return ensureLazyLoaded().then(() => {34 element = document.createElement('history-synced-device-manager');35 // |signInState| is generally set after |searchTerm| in Polymer 2. Set in36 // the same order in tests, in order to catch regressions like37 // https://crbug.com/915641.38 element.searchTerm = '';39 element.signInState = true;40 document.body.appendChild(element);41 });42 });43 test('single card, single window', function() {44 const sessionList = [createSession(45 'Nexus 5',46 [createWindow(['http://www.google.com', 'http://example.com'])])];47 setForeignSessions(sessionList);48 return flushTasks().then(function() {49 const card = element.$$('history-synced-device-card');50 assertEquals(51 'http://www.google.com',52 card.shadowRoot.querySelectorAll('.website-title')[0]53 .textContent.trim());54 assertEquals(2, card.tabs.length);55 });56 });57 test('two cards, multiple windows', function() {58 const sessionList = [59 createSession(60 'Nexus 5',61 [createWindow(['http://www.google.com', 'http://example.com'])]),62 createSession(63 'Nexus 6',64 [65 createWindow(['http://test.com']),66 createWindow(['http://www.gmail.com', 'http://badssl.com'])67 ]),68 ];69 setForeignSessions(sessionList);70 return flushTasks().then(function() {71 const cards = getCards(element);72 assertEquals(2, cards.length);73 // Ensure separators between windows are added appropriately.74 assertEquals(0, numWindowSeparators(cards[0]));75 assertEquals(1, numWindowSeparators(cards[1]));76 });77 });78 test('updating sessions', function() {79 const session1 = createSession(80 'Chromebook',81 [createWindow(['http://www.example.com', 'http://crbug.com'])]);82 session1.timestamp = 1000;83 const session2 =84 createSession('Nexus 5', [createWindow(['http://www.google.com'])]);85 setForeignSessions([session1, session2]);86 return flushTasks()87 .then(function() {88 const session1updated = createSession('Chromebook', [89 createWindow(['http://www.example.com', 'http://crbug.com/new']),90 createWindow(['http://web.site'])91 ]);92 session1updated.timestamp = 1234;93 setForeignSessions([session1updated, session2]);94 return flushTasks();95 })96 .then(function() {97 // There should only be two cards.98 const cards = getCards(element);99 assertEquals(2, cards.length);100 // There are now 2 windows in the first device.101 assertEquals(1, numWindowSeparators(cards[0]));102 // Check that the actual link changes.103 assertEquals(104 'http://crbug.com/new',105 cards[0]106 .shadowRoot.querySelectorAll('.website-title')[1]107 .textContent.trim());108 });109 });110 test('two cards, multiple windows, search', function() {111 const sessionList = [112 createSession(113 'Nexus 5',114 [createWindow(['http://www.google.com', 'http://example.com'])]),115 createSession(116 'Nexus 6',117 [118 createWindow(['http://www.gmail.com', 'http://badssl.com']),119 createWindow(['http://test.com']),120 createWindow(['http://www.gmail.com', 'http://bagssl.com'])121 ]),122 ];123 setForeignSessions(sessionList);124 return flushTasks()125 .then(function() {126 const cards = getCards(element);127 assertEquals(2, cards.length);128 // Ensure separators between windows are added appropriately.129 assertEquals(0, numWindowSeparators(cards[0]));130 assertEquals(2, numWindowSeparators(cards[1]));131 element.searchTerm = 'g';132 return flushTasks();133 })134 .then(function() {135 const cards = getCards(element);136 assertEquals(0, numWindowSeparators(cards[0]));137 assertEquals(1, cards[0].tabs.length);138 assertEquals('http://www.google.com', cards[0].tabs[0].title);139 assertEquals(1, numWindowSeparators(cards[1]));140 assertEquals(3, cards[1].tabs.length);141 assertEquals('http://www.gmail.com', cards[1].tabs[0].title);142 assertEquals('http://www.gmail.com', cards[1].tabs[1].title);143 assertEquals('http://bagssl.com', cards[1].tabs[2].title);144 // Ensure the title text is rendered during searches.145 assertEquals(146 'http://www.google.com',147 cards[0]148 .shadowRoot.querySelectorAll('.website-title')[0]149 .textContent.trim());150 element.searchTerm = 'Sans';151 return flushTasks();152 })153 .then(function() {154 assertEquals(0, getCards(element).length);155 assertNoSyncedTabsMessageShown(element, 'noSearchResults');156 });157 });158 test('delete a session', function() {159 const sessionList = [160 createSession('Nexus 5', [createWindow(['http://www.example.com'])]),161 createSession('Pixel C', [createWindow(['http://www.badssl.com'])]),162 ];163 setForeignSessions(sessionList);164 return flushTasks()165 .then(function() {166 const cards = getCards(element);167 assertEquals(2, cards.length);168 cards[0].$['menu-button'].click();169 return flushTasks();170 })171 .then(function() {172 element.$$('#menuDeleteButton').click();173 return testService.whenCalled('deleteForeignSession');174 })175 .then(args => {176 assertEquals('Nexus 5', args);177 // Simulate deleting the first device.178 setForeignSessions([sessionList[1]]);179 return flushTasks();180 })181 .then(function() {182 const cards = getCards(element);183 assertEquals(1, cards.length);184 assertEquals('http://www.badssl.com', cards[0].tabs[0].title);185 });186 });187 test('delete a collapsed session', function() {188 const sessionList = [189 createSession('Nexus 5', [createWindow(['http://www.example.com'])]),190 createSession('Pixel C', [createWindow(['http://www.badssl.com'])]),191 ];192 setForeignSessions(sessionList);193 return flushTasks()194 .then(function() {195 const cards = getCards(element);196 cards[0].$['card-heading'].click();197 assertFalse(cards[0].opened);198 // Simulate deleting the first device.199 setForeignSessions([sessionList[1]]);200 return flushTasks();201 })202 .then(function() {203 const cards = getCards(element);204 assertTrue(cards[0].opened);205 });206 });207 test('click synced tab', function() {208 setForeignSessions(209 [createSession('Chromebook', [createWindow(['https://example.com'])])]);210 return flushTasks()211 .then(function() {212 const cards = getCards(element);213 const anchor = cards[0].root.querySelector('a');214 anchor.click();215 return testService.whenCalled('openForeignSessionTab');216 })217 .then(args => {218 assertEquals('Chromebook', args.sessionTag, 'sessionTag is correct');219 assertEquals('123', args.windowId, 'windowId is correct');220 assertEquals(456, args.tabId, 'tabId is correct');221 assertFalse(args.e.altKey, 'altKey is defined');222 assertFalse(args.e.ctrlKey, 'ctrlKey is defined');223 assertFalse(args.e.metaKey, 'metaKey is defined');224 assertFalse(args.e.shiftKey, 'shiftKey is defined');225 });226 });227 test('show actions menu', function() {228 setForeignSessions(229 [createSession('Chromebook', [createWindow(['https://example.com'])])]);230 return flushTasks().then(function() {231 const cards = getCards(element);232 cards[0].$['menu-button'].click();233 assertTrue(element.$.menu.getIfExists().open);234 });235 });236 test('show sign in promo', function() {237 element.signInState = false;238 return flushTasks()239 .then(function() {240 assertFalse(element.$['sign-in-guide'].hidden);241 element.signInState = true;242 return flushTasks();243 })244 .then(function() {245 assertTrue(element.$['sign-in-guide'].hidden);246 });247 });248 test('no synced tabs message', function() {249 // When user is not logged in, there is no synced tabs.250 element.signInState = false;251 element.syncedDevices_ = [];252 return flushTasks()253 .then(function() {254 assertTrue(element.$['no-synced-tabs'].hidden);255 const cards = getCards(element);256 assertEquals(0, cards.length);257 element.signInState = true;258 return flushTasks();259 })260 .then(function() {261 // When user signs in, first show loading message.262 assertNoSyncedTabsMessageShown(element, 'loading');263 const sessionList = [];264 setForeignSessions(sessionList);265 return flushTasks();266 })267 .then(function() {268 const cards = getCards(element);269 assertEquals(0, cards.length);270 // If no synced tabs are fetched, show 'no synced tabs'.271 assertNoSyncedTabsMessageShown(element, 'noSyncedResults');272 const sessionList = [createSession(273 'Nexus 5',274 [createWindow(['http://www.google.com', 'http://example.com'])])];275 setForeignSessions(sessionList);276 return flushTasks();277 })278 .then(function() {279 const cards = getCards(element);280 assertEquals(1, cards.length);281 // If there are any synced tabs, hide the 'no synced tabs' message.282 assertTrue(element.$['no-synced-tabs'].hidden);283 element.signInState = false;284 return flushTasks();285 })286 .then(function() {287 // When user signs out, don't show the message.288 assertTrue(element.$['no-synced-tabs'].hidden);289 });290 });291 test('hide sign in promo in guest mode', function() {292 element.guestSession_ = true;293 return flushTasks().then(function() {294 assertTrue(element.$['sign-in-guide'].hidden);295 });296 });297 test('no synced tabs message displays on load', function() {298 element.syncedDevices_ = [];299 // Should show no synced tabs message on initial load. Regression test for300 // https://crbug.com/915641.301 return Promise.all([flushTasks(), waitBeforeNextRender(element)])302 .then(() => {303 assertNoSyncedTabsMessageShown(element, 'noSyncedResults');304 const cards = getCards(element);305 assertEquals(0, cards.length);306 });307 });...
capability-specs.js
Source:capability-specs.js
...15 logger.warn.restore();16 });17 it('should require platformName and deviceName', async function () {18 try {19 await d.createSession({});20 } catch (e) {21 e.should.be.instanceof(errors.SessionNotCreatedError);22 e.message.should.contain('platformName');23 return;24 }25 should.fail('error should have been thrown');26 });27 it('should require platformName', async function () {28 try {29 await d.createSession({'deviceName': 'Delorean'});30 } catch (e) {31 e.should.be.instanceof(errors.SessionNotCreatedError);32 e.message.should.contain('platformName');33 return;34 }35 should.fail('error should have been thrown');36 });37 it('should not care about cap order', async function () {38 await d.createSession({39 deviceName: 'Delorean',40 platformName: 'iOS'41 });42 });43 it('should check required caps which are added to driver', async function () {44 d.desiredCapConstraints = {45 necessary: {46 presence: true47 },48 proper: {49 presence: true,50 isString: true,51 inclusion: ['Delorean', 'Reventon']52 }53 };54 try {55 await d.createSession({56 'platformName': 'iOS',57 'deviceName': 'Delorean'58 });59 } catch (e) {60 e.should.be.instanceof(errors.SessionNotCreatedError);61 e.message.should.contain('necessary');62 e.message.should.contain('proper');63 return;64 }65 should.fail('error should have been thrown');66 });67 it('should check added required caps in addition to base', async function () {68 d.desiredCapConstraints = {69 necessary: {70 presence: true71 },72 proper: {73 presence: true,74 isString: true,75 inclusion: ['Delorean', 'Reventon']76 }77 };78 try {79 await d.createSession({80 necessary: 'yup',81 proper: 'yup, your highness'82 });83 } catch (e) {84 e.should.be.instanceof(errors.SessionNotCreatedError);85 e.message.should.contain('platformName');86 return;87 }88 should.fail('error should have been thrown');89 });90 it('should accept extra capabilities', async function () {91 await d.createSession({92 'platformName': 'iOS',93 'deviceName': 'Delorean',94 'extra': 'cheese',95 'hold the': 'sauce'96 });97 });98 it('should log the use of extra caps', async function () {99 this.timeout(500);100 await d.createSession({101 'platformName': 'iOS',102 'deviceName': 'Delorean',103 'extra': 'cheese',104 'hold the': 'sauce'105 });106 logger.warn.callCount.should.be.above(0);107 });108 it('should be sensitive to the case of caps', async function () {109 try {110 await d.createSession({111 'platformname': 'iOS',112 'deviceName': 'Delorean'113 });114 } catch (e) {115 e.should.be.instanceof(errors.SessionNotCreatedError);116 e.message.should.contain('platformName');117 return;118 }119 should.fail('error should have been thrown');120 });121 describe('boolean capabilities', function () {122 it('should allow a string "false"', async function () {123 await d.createSession({124 'platformName': 'iOS',125 'deviceName': 'Delorean',126 'noReset': 'false'127 });128 logger.warn.callCount.should.be.above(0);129 let sessions = await d.getSessions();130 sessions[0].capabilities.noReset.should.eql(false);131 });132 it('should allow a string "true"', async function () {133 await d.createSession({134 'platformName': 'iOS',135 'deviceName': 'Delorean',136 'noReset': 'true'137 });138 logger.warn.callCount.should.be.above(0);139 let sessions = await d.getSessions();140 sessions[0].capabilities.noReset.should.eql(true);141 });142 it('should allow a string "true" in string capabilities', async function () {143 await d.createSession({144 'platformName': 'iOS',145 'deviceName': 'Delorean',146 'language': 'true'147 });148 logger.warn.callCount.should.equal(0);149 let sessions = await d.getSessions();150 sessions[0].capabilities.language.should.eql('true');151 });152 });153 describe('number capabilities', function () {154 it('should allow a string "1"', async function () {155 await d.createSession({156 'platformName': 'iOS',157 'deviceName': 'Delorean',158 'newCommandTimeout': '1'159 });160 logger.warn.callCount.should.be.above(0);161 let sessions = await d.getSessions();162 sessions[0].capabilities.newCommandTimeout.should.eql(1);163 });164 it('should allow a string "1.1"', async function () {165 await d.createSession({166 'platformName': 'iOS',167 'deviceName': 'Delorean',168 'newCommandTimeout': '1.1'169 });170 logger.warn.callCount.should.be.above(0);171 let sessions = await d.getSessions();172 sessions[0].capabilities.newCommandTimeout.should.eql(1.1);173 });174 it('should allow a string "1" in string capabilities', async function () {175 await d.createSession({176 'platformName': 'iOS',177 'deviceName': 'Delorean',178 'language': '1'179 });180 logger.warn.callCount.should.equal(0);181 let sessions = await d.getSessions();182 sessions[0].capabilities.language.should.eql('1');183 });184 });185 it ('should error if objects in caps', async function () {186 try {187 await d.createSession({188 'platformName': {a: 'iOS'},189 'deviceName': 'Delorean'190 });191 } catch (e) {192 e.should.be.instanceof(errors.SessionNotCreatedError);193 e.message.should.contain('platformName');194 return;195 }196 should.fail('error should have been thrown');197 });198 it('should check for deprecated caps', async function () {199 this.timeout(500);200 d.desiredCapConstraints = {201 'lynx-version': {202 deprecated: true203 }204 };205 await d.createSession({206 'platformName': 'iOS',207 'deviceName': 'Delorean',208 'lynx-version': 5209 });210 logger.warn.callCount.should.be.above(0);211 });212 it('should not warn if deprecated=false', async function () {213 this.timeout(500);214 d.desiredCapConstraints = {215 'lynx-version': {216 deprecated: false217 }218 };219 await d.createSession({220 'platformName': 'iOS',221 'deviceName': 'Delorean',222 'lynx-version': 5223 });224 logger.warn.callCount.should.equal(0);225 });226 it('should not validate against null/undefined caps', async function () {227 d.desiredCapConstraints = {228 'foo': {229 isString: true230 }231 };232 await d.createSession({233 platformName: 'iOS',234 deviceName: 'Dumb',235 foo: null236 });237 await d.deleteSession();238 await d.createSession({239 platformName: 'iOS',240 deviceName: 'Dumb',241 foo: 1242 }).should.eventually.be.rejectedWith(/was not valid/);243 await d.createSession({244 platformName: 'iOS',245 deviceName: 'Dumb',246 foo: undefined247 });248 await d.deleteSession();249 await d.createSession({250 platformName: 'iOS',251 deviceName: 'Dumb',252 foo: ''253 });254 await d.deleteSession();255 });256 it('should still validate null/undefined/empty caps whose presence is required', async function () {257 d.desiredCapConstraints = {258 foo: {259 presence: true260 },261 };262 await d.createSession({263 platformName: 'iOS',264 deviceName: 'Dumb',265 foo: null266 }).should.eventually.be.rejectedWith(/blank/);267 await d.createSession({268 platformName: 'iOS',269 deviceName: 'Dumb',270 foo: ''271 }).should.eventually.be.rejectedWith(/blank/);272 await d.createSession({273 platformName: 'iOS',274 deviceName: 'Dumb',275 foo: {}276 }).should.eventually.be.rejectedWith(/blank/);277 await d.createSession({278 platformName: 'iOS',279 deviceName: 'Dumb',280 foo: []281 }).should.eventually.be.rejectedWith(/blank/);282 await d.createSession({283 platformName: 'iOS',284 deviceName: 'Dumb',285 foo: ' '286 }).should.eventually.be.rejectedWith(/blank/);287 });288 describe('w3c', function () {289 it('should accept w3c capabilities', async function () {290 const [sessionId, caps] = await d.createSession(null, null, {291 alwaysMatch: {292 platformName: 'iOS',293 deviceName: 'Delorean'294 }, firstMatch: [{}],295 });296 sessionId.should.exist;297 caps.should.eql({298 platformName: 'iOS',299 deviceName: 'Delorean',300 });301 await d.deleteSession();302 });303 it('should ignore w3c capabilities if it is not a plain JSON object', async function () {304 for (let val of [true, 'string', [], 100]) {305 const [sessionId, caps] = await d.createSession({306 platformName: 'iOS',307 deviceName: 'Delorean'308 }, null, val);309 sessionId.should.exist;310 caps.should.eql({311 platformName: 'iOS',312 deviceName: 'Delorean',313 });314 await d.deleteSession();315 }316 });317 });...
sessions.test.js
Source:sessions.test.js
1const supertest = require('supertest');2const app = require('../../src/app');3const Session = require('../../src/models/session');4const { connectToDB } = require('../../src/utils/db');5const request = supertest(app);6describe('/sessions', () => {7 beforeAll(() => {8 connectToDB();9 });10 beforeEach(async () => {11 await Session.deleteMany({});12 });13 const validSession = { date: '2021-06-28', time: 0, maxNumber: 50 };14 const formatValidator = [15 { field: 'date', value: undefined },16 { field: 'time', value: undefined },17 { field: 'maxNumber', value: undefined },18 { field: 'date', value: '2-06-01' },19 { field: 'date', value: '2021-006-01' },20 { field: 'date', value: '2021-06-001' },21 { field: 'date', value: '20211-06-01' },22 { field: 'date', value: '2021.06.01' },23 { field: 'time', value: 'abc' },24 { field: 'maxNumber', value: 'abc' },25 ];26 //= =================== POST TEST ====================27 describe('POST', () => {28 const createSession = (body) => request.post('/api/sessions').send(body);29 it('should return 201 if request is valid', async () => {30 const res = await createSession(validSession);31 expect(res.statusCode).toBe(201);32 });33 it('should save session to database if request is valid', async () => {34 await createSession(validSession);35 const session = await Session.findOne({36 date: validSession.date,37 time: validSession.time,38 });39 expect(!!session).toBe(true);40 });41 it.each(formatValidator)(42 'should return 400 when $field is $value',43 async ({ field, value }) => {44 const session = { ...validSession };45 session[field] = value;46 const res = await createSession(session);47 expect(res.statusCode).toBe(400);48 },49 );50 it('should return 409 if the new session is already existed', async () => {51 await createSession(validSession);52 const res = await createSession(validSession);53 expect(res.statusCode).toBe(409);54 });55 });56 //= =================== GET TEST ====================57 describe('GET', () => {58 const requestingSession = { date: '2021-06-28', time: 0 };59 const createSession = (body) => request.post('/api/sessions').send(body);60 const getSession = (params) => request.get(`/api/sessions/single/${params.date}/${params.time}`);61 it('should return 200 if request finds the target', async () => {62 await createSession(validSession);63 const res = await getSession(requestingSession);64 expect(res.statusCode).toBe(200);65 });66 it.each(formatValidator)(67 'should return 400 if request is invalid',68 async ({ field, value }) => {69 await createSession(validSession);70 const session = { ...requestingSession };71 if (!session[field]) {72 return;73 }74 session[field] = value;75 const res = await getSession(session);76 expect(res.statusCode).toBe(400);77 },78 );79 it('should return 404 if request is not found', async () => {80 await createSession(validSession);81 const session = { ...requestingSession };82 session.date = '2021-06-27';83 const res = await getSession(session);84 expect(res.statusCode).toBe(404);85 });86 });87 //= =================== PUT TEST ====================88 describe('PUT', () => {89 const newDateAndTime = { date: '2021-06-28', time: 0 };90 const newMaxNumber = { maxNumber: 40 };91 const createSession = (body) => request.post('/api/sessions').send(body);92 const updateSession = (params, body) => request.put(`/api/sessions/${params.date}/${params.time}`).send(body);93 it('should return 200 if session updates successfully', async () => {94 await createSession(validSession);95 const res = await updateSession(newDateAndTime, newMaxNumber);96 expect(res.statusCode).toBe(200);97 });98 it.each(formatValidator)(99 'should return 400 if request is invalid',100 async ({ field, value }) => {101 await createSession(validSession);102 const dateAndTime = { ...newDateAndTime };103 const maxNumber = { ...newMaxNumber };104 if (field === 'maxNumber') {105 maxNumber[field] = value;106 } else {107 dateAndTime[field] = value;108 }109 const res = await updateSession(dateAndTime, maxNumber);110 expect(res.statusCode).toBe(400);111 },112 );113 it('should return 404 if request is not found', async () => {114 await createSession(validSession);115 const dateAndTime = { ...newDateAndTime };116 dateAndTime.date = '2021-06-27';117 const res = await updateSession(dateAndTime, newMaxNumber);118 expect(res.statusCode).toBe(404);119 });120 });121 //= =================== DELETE TEST ====================122 describe('DELETE', () => {123 const sessionToBeDelete = { date: '2021-06-28', time: 0 };124 const createSession = (body) => request.post('/api/sessions').send(body);125 const deleteSession = (params) => request.delete(`/api/sessions/${params.date}/${params.time}`);126 it('should return 204 if request is valie', async () => {127 await createSession(validSession);128 const res = await deleteSession(sessionToBeDelete);129 expect(res.statusCode).toBe(204);130 });131 it('should return 404 if request is not found', async () => {132 await createSession(validSession);133 const session = { ...sessionToBeDelete };134 session.date = '2021-06-27';135 const res = await deleteSession(session);136 expect(res.statusCode).toBe(404);137 });138 it.each(formatValidator)(139 'should return 400 if request is invalid',140 async ({ field, value }) => {141 await createSession(validSession);142 const session = { ...sessionToBeDelete };143 if (!session[field]) {144 return;145 }146 session[field] = value;147 const res = await deleteSession(session);148 expect(res.statusCode).toBe(400);149 },150 );151 });...
Login.js
Source:Login.js
1import React, { useState } from "react";2import {Form, Button, FormGroup, FormControl, FormLabel } from "react-bootstrap";3import "./Login.css";4import logo from "../images/logoGosst.png";5import LogicCallssss from "../util/utilClass.js";6export default function Login() {7 const [user, setUser] = useState("");8 const [password, setPassword] = useState("");9 const [msg, setMsg] = useState("");10 function validateForm() {11 return user.length > 0 && password.length > 0;12 }13 function handleSubmit(event) {14 event.preventDefault();15 const dataParam = {16 userName : user,17 password : password18 }19 20 LogicCallssss.callAjaxPost("login/validated",dataParam,(data)=>{21 console.log(data);22 procesarRespuesta(data);23 });24 }25 return (26 <div className="Login">27 <h6>Gestor Online de Seguridad y Salud en el Trabajo</h6>28 <img src={logo} alt="logoGosst" height="200px"/>29 {30 // <h5>Enter the system</h5> 31 }32 <Form onSubmit={handleSubmit}>33 <FormGroup controlId="user" >34 <FormLabel>User</FormLabel>35 <FormControl36 autoFocus37 type="text"38 value={user}39 onChange={e => setUser(e.target.value)}40 />41 </FormGroup>42 <FormGroup controlId="password" >43 <FormLabel>Password</FormLabel>44 <FormControl45 value={password}46 onChange={e => setPassword(e.target.value)}47 type="password"48 />49 </FormGroup>50 <Button block disabled={!validateForm()} type="submit">51 Login52 </Button>53 <div className="msgAlert" >{msg}</div>54 </Form>55 56 <a className="efectoLink" href="https://www.gosst.io">Forgot Password?</a>57 </div>58 );59 function procesarRespuesta(data) {60 setMsg("");61 if (data.CODE_RESPONSE === "02") {62 setMsg("Usuario y/o contraseña incorrectos.");63 } else if (data.CODE_RESPONSE === "03") {64 setMsg("Usuario está bloqueado, intentelo dentro de 2 minutos.");65 } else if (data.CODE_RESPONSE === "11") {66 setMsg("Usuario no existe");67 } else if (data.CODE_RESPONSE === "13") {68 setMsg("Contratista no activo en la empresa");69 } else if (data.CODE_RESPONSE === "14") {70 setMsg("Trabajador retirado de la empresa");71 } else if (data.CODE_RESPONSE === "01") {72 var clasifs = data.listaClasificaciones;73 var pels = data.mapPeligros;74 var riesgos = data.mapRiesgos;75 LogicCallssss.createSession("moduloGosstId", data.moduloId);76 LogicCallssss.createSession("gestopcompanyid", data.empresaId);77 LogicCallssss.createSession("gestopcompanyname", data.empresaNombre);78 79 LogicCallssss.createSession("clasifs", JSON.stringify(clasifs));80 LogicCallssss.createSession("peligros", JSON.stringify(pels));81 LogicCallssss.createSession("riesgos", JSON.stringify(riesgos));82 //createSession("gestopusername", data.usuarioNombre);83 LogicCallssss.createSession("numEmpresas", data.numEmpresas);84 LogicCallssss.createSession("numUnidades", data.numUnidades);85 LogicCallssss.createSession("trabajadorGosstId", data.trabajadorId);86 LogicCallssss.createSession("contratistaGosstId", data.contratistaId);87 LogicCallssss.createSession("unidadGosstId", data.trabajadorUnidadId);88 LogicCallssss.createSession("areaGosstId", data.trabajadorAreaId);89 LogicCallssss.createSession("puestoGosstId", data.trabajadorPuestoId);90 LogicCallssss.createSession("fechaActualizacionPuesto", data.trabajadorFechaPuesto);91 LogicCallssss.createSession("accesoGerencia", data.accesoGerencia);92 93 LogicCallssss.createSession("accesoUsuarios", data.accesoUsuarios);94 LogicCallssss.createSession("hasTutorialCap", data.hasTutorialCap);95 LogicCallssss.createSession("gestopInicio",0);96 LogicCallssss.createSession("modulo", "Modulos");97 98 document.location.href=(data.PATH.split(".")[0]);99 100 } else {101 setMsg("<b>Usuario incorrecto.</b>");102 }103}...
createSession.js
Source:createSession.js
1/**2 * Module dependencies3 */4var assert = require('assert'),5 check = require('validator').check;6/**7 * Fixtures8 */9var DZ = require('../');10var deezer = new DZ();11describe('deezer#createSession()', function() {12 describe('callback', function() {13 it('should fire', function (cb) {14 deezer.createSession('asddg4sgdagsd', '8j4ajdgkasdgjasdg', 'asdgasagsdsgd', function (err) {15 // Ignore error, since inputs are clearly invalid16 // Instead validate that this callback fires at all17 cb();18 });19 });20 it('should contain error when crazy, random inputs are used', function (cb) {21 deezer.createSession('asddg4sgda$*(ADADGHADhagsd', '8j4ajdgkasdgjasaAFHOdg', 'asDdgasagsdsgd', function (err) {22 // If there is no error, there is something wrong23 if (!err) return cb(new Error('createSession() should have responded w/ an error!'));24 cb();25 });26 });27 });28 describe('proper behavior for invalid input', function() {29 it('should throw when `appId` is invalid or not present', function() {30 assert.throws(function() { deezer.createSession(); });31 assert.throws(function() { deezer.createSession( {} ); });32 assert.throws(function() { deezer.createSession( [] ); });33 assert.throws(function() { deezer.createSession( function bigNastyWrongThing() {} ); });34 });35 it('should throw when `code` is invalid or not present', function() {36 assert.throws(function() { deezer.createSession('asddg4sgdagsd'); });37 assert.throws(function() { deezer.createSession('asddg4sgdagsd', 235235 ); });38 assert.throws(function() { deezer.createSession('asddg4sgdagsd', {} ); });39 assert.throws(function() { deezer.createSession('asddg4sgdagsd', [] ); });40 assert.throws(function() { deezer.createSession('asddg4sgdagsd', function bigNastyWrongThing() {} ); });41 });42 it('should throw when `secret` is invalid or not present', function() {43 assert.throws(function() { deezer.createSession('asddg4sgdagsd', '82hgahdsgha49'); });44 assert.throws(function() { deezer.createSession('asddg4sgdagsd', '82hgahdsgha49', 235235 ); });45 assert.throws(function() { deezer.createSession('asddg4sgdagsd', '82hgahdsgha49', {} ); });46 assert.throws(function() { deezer.createSession('asddg4sgdagsd', '82hgahdsgha49', [] ); });47 assert.throws(function() { deezer.createSession('asddg4sgdagsd', '82hgahdsgha49', function bigNastyWrongThing() {} ); });48 });49 it('should throw when `cb` is invalid or not present', function() {50 assert.throws(function() { deezer.createSession('asddg4sgdagsd', '82hgahdsgha49', 'ag4asdjgajasdg'); });51 assert.throws(function() { deezer.createSession('asddg4sgdagsd', '82hgahdsgha49', 'ag4asdjgajasdg', 235235 ); });52 assert.throws(function() { deezer.createSession('asddg4sgdagsd', '82hgahdsgha49', 'ag4asdjgajasdg', {} ); });53 assert.throws(function() { deezer.createSession('asddg4sgdagsd', '82hgahdsgha49', 'ag4asdjgajasdg', [] ); });54 assert.throws(function() { deezer.createSession('asddg4sgdagsd', '82hgahdsgha49', 'ag4asdjgajasdg', 'sadggsad'); });55 });56 it('should not throw when required arguments are present and valid', function () {57 deezer.createSession('2z49h4a--DA FHIË Ã¸Ã¸Ã®Ã¼Ã¯Ã¸284', 'asdgjg9sdj9sdgaj', 'adgsdgasdgasdg', function someCb() {} );58 });59 });...
session.js
Source:session.js
1const expect = require('chai').expect2const createSession = require('../lib/index').createSession3describe('createSession', () => {4 it('should be a function', () => {5 expect(createSession).to.be.a('function')6 })7 describe('params', () => {8 it('should throw no options error', () => {9 expect(createSession).to.throw('You must specify options!')10 })11 it('should throw no auth id or key error', () => {12 expect(createSession.bind(undefined, {})).to.throw('You must specify auth id and key!')13 })14 it('should throw no auth id or key error', () => {15 expect(createSession.bind(undefined, {16 auth_id: 133717 })).to.throw('You must specify auth id and key!')18 })19 it('should throw no auth id or key error', () => {20 expect(createSession.bind(undefined, {21 auth_key: 'FFFF1337'22 })).to.throw('You must specify auth id and key!')23 })24 })...
Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2 until = webdriver.until;3var driver = new webdriver.Builder()4 .forBrowser('chrome')5 .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();10var webdriver = require('selenium-webdriver'),11 until = webdriver.until;12var driver = new webdriver.Builder()13 .forBrowser('chrome')14 .build();15driver.findElement(By.name('q')).sendKeys('webdriver');16driver.findElement(By.name('btnG')).click();17driver.wait(until.titleIs('webdriver - Google Search'), 1000);18driver.quit();19var webdriver = require('selenium-webdriver'),20 until = webdriver.until;21var driver = new webdriver.Builder()22 .forBrowser('chrome')23 .build();24driver.findElement(By.name('q')).sendKeys('webdriver');25driver.findElement(By.name('btnG')).click();26driver.wait(until.titleIs('webdriver - Google Search'), 1000);27driver.quit();28var webdriver = require('selenium-webdriver'),29 until = webdriver.until;30var driver = new webdriver.Builder()31 .forBrowser('chrome')32 .build();33driver.findElement(By.name('q')).sendKeys('webdriver');34driver.findElement(By.name('btnG')).click();35driver.wait(until.titleIs('webdriver - Google Search'), 1000);36driver.quit();37var webdriver = require('selenium-webdriver'),38 until = webdriver.until;39var driver = new webdriver.Builder()40 .forBrowser('chrome')41 .build();
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2 build();3driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');4driver.findElement(webdriver.By.name('btnG')).click();5driver.wait(function() {6 return driver.getTitle().then(function(title) {7 return title === 'webdriver - Google Search';8 });9}, 1000);10driver.quit();
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var By = webdriver.By;3var until = webdriver.until;4var driver = new webdriver.Builder().forBrowser('chrome').build();5driver.findElement(By.name('q')).sendKeys('webdriver');6driver.findElement(By.name('btnG')).click();7driver.wait(until.titleIs('webdriver - Google Search'), 1000);8driver.quit();
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!