Best JavaScript code snippet using playwright-internal
index.js
Source:index.js
1var assert = require("assert");2var sinon = require("sinon");3var path = require("path");4var fs = require("fs");5var connector;6var Connector;7var noop = function () {};8describe("index.js", function () {9 var winston = {10 clear: sinon.stub(),11 add: sinon.stub(),12 info: sinon.stub(),13 debug: sinon.stub(),14 warn: sinon.stub(),15 error: sinon.stub(),16 verbose: sinon.stub(),17 transports: { Console: {} }18 };19 beforeEach(function () {20 winston.clear.reset();21 winston.add.reset();22 winston.info.reset();23 winston.debug.reset();24 winston.warn.reset();25 winston.error.reset();26 winston.verbose.reset();27 });28 describe("class", function () {29 describe("before module was initialied", function () {30 it("should fail", function () {31 try {32 require.uncache("../index.js");33 connector = require("../index.js");34 Connector = connector.Connector;35 new Connector();36 assert.fail("should not reach here!");37 } catch (e) {38 assert.ok(e instanceof Error);39 assert.equal(e.message, "'kido-connector' was not initialized.");40 }41 });42 });43 describe("after module was initialized.", function () {44 var createSession = sinon.stub();45 var refreshSession = sinon.stub();46 var disposeSession = sinon.stub();47 var opts;48 before(function () {49 require.uncache("../index.js");50 connector = require("../index.js");51 Connector = connector.Connector;52 connector.init("test", winston);53 });54 beforeEach(function () {55 createSession.reset();56 refreshSession.reset();57 disposeSession.reset();58 opts = {59 };60 });61 describe("constructor", function () {62 it("should fail on invalid opts", function () {63 [64 0,65 "",66 "foo",67 true,68 []69 ].forEach(function (opts) {70 try {71 new Connector(opts);72 assert.fail("should not reach here!");73 } catch (e) {74 assert.ok(e instanceof Error);75 assert.equal(e.message, "'opts' argument must be an object instance.");76 }77 });78 });79 it("should fail on invalid opts.config.", function () {80 [81 10,82 "foo",83 false,84 true,85 []86 ]87 .forEach(function (config) {88 try {89 opts.config = config;90 new Connector(opts);91 assert.fail("should not reach here!");92 } catch (e) {93 assert.ok(e instanceof Error);94 assert.equal(e.message, "'opts.config' property is missing or invalid.");95 }96 });97 });98 it("should fail on invalid opts.config.timeout.", function () {99 [100 10,101 "1000",102 [],103 {}104 ]105 .forEach(function (value) {106 try {107 opts.config = { timeout: value };108 new Connector(opts);109 assert.fail("should not reach here!");110 } catch (e) {111 assert.ok(e instanceof Error);112 assert.equal(e.message, "'opts.config.timeout' property must be a number equal or greater than 100.");113 }114 });115 });116 it("should fail on invalid opts.credentialProps", function () {117 [118 0,119 "",120 "foo",121 true,122 {}123 ].forEach(function (credentialProps) {124 try {125 opts.credentialProps = credentialProps;126 new Connector(opts);127 assert.fail("should not reach here!");128 } catch (e) {129 assert.ok(e instanceof Error);130 assert.equal(e.message, "'opts.credentialProps' property must be an array of strings.");131 }132 });133 });134 it("should fail on invalid opts.createSessionCb", function () {135 [136 0,137 "",138 "foo",139 true,140 {},141 []142 ].forEach(function (createSession) {143 try {144 opts.createSessionCb = createSession;145 new Connector(opts);146 assert.fail("should not reach here!");147 } catch (e) {148 assert.ok(e instanceof Error);149 assert.equal(e.message, "'opts.createSessionCb' property is missing or invalid.");150 }151 });152 });153 it("should fail on invalid opts.disposeSession", function () {154 [155 1,156 "foo",157 true,158 {},159 []160 ].forEach(function (disposeSession) {161 try {162 opts.disposeSessionCb = disposeSession;163 new Connector(opts);164 assert.fail("should not reach here!");165 } catch (e) {166 assert.ok(e instanceof Error);167 assert.equal(e.message, "'opts.disposeSessionCb' property must be a function.");168 }169 });170 });171 it("should fail on invalid opts.refreshSession", function () {172 [173 1,174 "foo",175 true,176 {},177 []178 ].forEach(function (refreshSession) {179 try {180 opts.refreshSessionCb = refreshSession;181 new Connector(opts);182 assert.fail("should not reach here!");183 } catch (e) {184 assert.ok(e instanceof Error);185 assert.equal(e.message, "'opts.refreshSessionCb' property must be a function.");186 }187 });188 });189 it("should be able to create an instance.", function (done) {190 var c = new Connector(opts);191 assert.ok(c instanceof Connector);192 done();193 });194 });195 describe("getSession", function () {196 beforeEach(function () {197 opts.credentialProps = ["username", "password"];198 opts.createSessionCb = createSession;199 opts.refreshSessionCb = refreshSession;200 opts.disposeSessionCb = disposeSession;201 });202 it("should fail if no options argument was passed on.", function (done) {203 var values = [204 null,205 undefined,206 true,207 1000,208 "",209 "foo"210 ];211 var c = new Connector(opts);212 values.forEach(function (value) {213 c.getSession(value, function (err, data) {214 assert.ok(err instanceof Error);215 assert.equal(err.message, "'options' argument must be an object instance.");216 if (value===values[values.length-1]) done();217 });218 });219 });220 it("should fail when the options that was passed on is not an object instance.", function (done) {221 var values = [222 "",223 true,224 1000,225 null,226 undefined,227 []228 ];229 var c = new Connector(opts);230 values.forEach(function (value) {231 c.getSession(value, function (err, data) {232 assert.ok(err instanceof Error);233 assert.equal(err.message, "'options' argument must be an object instance.");234 if (value===values[values.length-1]) done();235 });236 });237 });238 it("should return any error returned by createSessionCb callback.", function (done) {239 var c = new Connector(opts);240 createSession.onCall(0).callsArgWith(1, "some error");241 c.getSession({ username: "mike" }, function (err, data) {242 assert.ok(createSession.calledOnce);243 assert.ok(!data);244 assert.equal(err, "some error");245 done();246 });247 });248 it("should return an error if an invalid 'auth' token was passed on.", function (done) {249 var c = new Connector(opts);250 c.getSession({ auth: "un existing token" }, function (err, data) {251 assert.ok(!data);252 assert.ok(err instanceof Error);253 assert.equal(err.message, "Invalid 'auth' token.");254 done();255 });256 });257 it("should work when valid arguments", function (done) {258 var c = new Connector(opts);259 createSession.onCall(0).callsArgWith(1, null, "token");260 c.getSession({ username: "mike" }, function (err, data) {261 assert.ok(createSession.calledOnce);262 assert.ok(data);263 assert.equal(data, "token");264 done();265 });266 });267 it("should only call createSession once when valid arguments", function (done) {268 var c = new Connector(opts);269 createSession.onCall(0).callsArgWith(1, null, "token");270 c.getSession({ username: "mike" }, function (err, data) {271 assert.ok(!err);272 c.getSession({ username: "mike" }, function (err, data) {273 assert.ok(createSession.calledOnce);274 done();275 });276 });277 });278 it("should ignore cache if 'ignoreCache' option is passed", function (done) {279 var c = new Connector(opts);280 createSession.onCall(0).callsArgWith(1, null, "token");281 createSession.onCall(1).callsArgWith(1, null, "new-token");282 c.getSession({ username: "mike" }, function (err, data) {283 assert.ok(!err);284 c.getSession({ username: "mike", ignoreCache: true }, function (err, data) {285 assert.ok(!err);286 assert.equal(data, "new-token");287 done();288 });289 });290 });291 describe("When cache are disabled", function () {292 it("should invoke createSessionCb always", function (done) {293 opts.disableCache = true;294 delete opts.refreshSessionCb;295 delete opts.disposeSessionCb;296 var c = new Connector(opts);297 createSession.onCall(0).callsArgWith(1, null, { auth: "custom" });298 createSession.onCall(1).callsArgWith(1, null, { auth: "custom2" });299 c.getSession( {}, function (err, session, auth) {300 assert.ok(createSession.calledOnce);301 assert.ok(!err);302 assert.equal(session.auth, "custom");303 assert.equal(auth, "custom");304 c.getSession( {}, function (err, session, auth) {305 assert.ok(createSession.calledTwice);306 assert.ok(!err);307 assert.equal(session.auth, "custom2");308 assert.equal(auth, "custom2");309 done();310 });311 });312 });313 it("should fail if session doesn't have 'auth' prop", function (done) {314 opts.disableCache = true;315 delete opts.refreshSessionCb;316 delete opts.disposeSessionCb;317 var c = new Connector(opts);318 createSession.onCall(0).callsArgWith(1, null, {});319 c.getSession( {}, function (err, session, auth) {320 assert.ok(createSession.calledOnce);321 assert.ok(err instanceof Error);322 assert.equal(err.message, "session doesn't have 'auth' property.");323 done();324 });325 });326 });327 describe("When an user hasn't a session.", function () {328 describe("and user credentials were not configured", function () {329 it("should invoke createSessionCb callback.", function (done) {330 var c = new Connector(opts);331 createSession.onCall(0).callsArgWith(1, null, "custom");332 c.getSession({ }, function (err, session, auth) {333 assert.ok(createSession.calledOnce);334 assert.ok(!err);335 assert.equal(session, "custom");336 assert.ok(auth);337 done();338 });339 });340 });341 describe("and user credentials were configured", function () {342 beforeEach(function () {343 opts.config = { username: "foo", password: "bar" };344 });345 it("should use configured credentials when no credentials were passed on.", function (done) {346 var c = new Connector(opts);347 c.getSession({}, function (err, session, auth) {348 assert.ok(!err);349 assert.ok(session);350 assert.ok(auth);351 assert.ok(createSession.calledOnce);352 var args = createSession.getCall(0).args;353 assert.deepEqual(args[0], { username: "foo", password: "bar" });354 done();355 });356 });357 it("should use passed on credentials.", function (done) {358 var c = new Connector(opts);359 c.getSession({ username: "alfa", password: "beta"}, function (err, session, auth) {360 assert.ok(!err);361 assert.ok(session);362 assert.ok(auth);363 assert.ok(createSession.calledOnce);364 var args = createSession.getCall(0).args;365 assert.deepEqual(args[0], { username: "alfa", password: "beta" });366 done();367 });368 });369 });370 });371 describe("When a user has an existing session.", function () {372 it("should return data from cache if a valid auth token was passed on.", function (done) {373 var c = new Connector(opts);374 createSession.onCall(0).callsArgWith(1, null, "custom");375 c.getSession({ username: "mike", password: "1234" }, function (err, session, auth) {376 assert.ok(!err);377 assert.ok(session);378 assert.ok(auth);379 c.getSession({ auth: auth }, function (err, session2, auth2) {380 assert.ok(!refreshSession.called);381 assert.ok(!err);382 assert.equal(session, session2);383 assert.equal(auth, auth2);384 done();385 });386 });387 });388 it("should return data from cache if a valid username and password were passed on.", function (done) {389 var c = new Connector(opts);390 createSession.onCall(0).callsArgWith(1, null, "custom");391 c.getSession({ username: "mike", password: "1234" }, function (err, session, auth) {392 assert.ok(!err);393 assert.ok(session);394 assert.ok(auth);395 c.getSession({ username: "mike", password: "1234" }, function (err, session2, auth2) {396 assert.ok(!err);397 assert.equal(session, session2);398 assert.equal(auth, auth2);399 done();400 });401 });402 });403 it("should fail if a valid username but wrong password were passed on.", function (done) {404 var c = new Connector(opts);405 createSession.onCall(0).callsArgWith(1, null, "custom");406 createSession.onCall(1).callsArgWith(1, "some error");407 c.getSession({ username: "mike", password: "1234" }, function (err, session, auth) {408 assert.ok(!err);409 assert.ok(session);410 assert.ok(auth);411 c.getSession({ username: "mike", password: "5678" }, function (err, session2, auth2) {412 assert.ok(!session2);413 assert.ok(!auth2);414 assert.equal(err, "some error");415 // valiate createSession calls' arguments416 assert.deepEqual(createSession.getCall(0).args[0], { username: "mike", password: "1234" });417 assert.deepEqual(createSession.getCall(1).args[0], { username: "mike", password: "5678" });418 done();419 });420 });421 });422 describe("And module was initialized with a 'refreshSessionCb' callback", function () {423 it("should return any error returned by refreshSession callback.", function (done) {424 var c = new Connector(opts);425 createSession.onCall(0).callsArgWith(1, null, "custom", new Date());426 c.getSession({ username: "mike" }, function (err, session, auth) {427 assert.ok(!err);428 assert.ok(session);429 assert.ok(auth);430 // refresh authentication and returns new metadata and new expiration431 refreshSession.onCall(0).callsArgWith(1, "some error");432 // wait until token expires433 setTimeout(function () {434 // token is expired, a new getSession must refresh the token435 c.getSession({ auth: auth }, function (err, session2, auth2) {436 assert.ok(refreshSession.calledOnce);437 assert.ok(!session2);438 assert.ok(!auth2);439 assert.equal(err, "some error");440 done();441 });442 }, 20);443 });444 });445 it("should invoke 'refreshSession' callback when auth token is expired.", function (done) {446 var firstDate = new Date();447 var secondDate = new Date(firstDate.getTime() + 5000);448 // authenticates user and returns metadata and expiration449 // firstDate is an expired time450 createSession.onCall(0).callsArgWith(1, null, "custom", firstDate);451 // refresh authentication and returns new metadata and new expiration452 refreshSession.onCall(0).callsArgWith(1, null, "custom2", secondDate);453 var c = new Connector(opts);454 // first getSession users455 c.getSession({ username: "mike", password: "1234" }, function (err, session, auth) {456 assert.ok(!err);457 assert.ok(auth);458 assert.equal(session, "custom");459 // wait until token expires460 setTimeout(function () {461 // token is expired, a new getSession must refresh the token462 c.getSession({ auth: auth }, function (err, session2, auth2) {463 assert.ok(!err);464 // auth token must remain the same one465 assert.equal(auth2, auth);466 // the session must be the new one467 assert.equal(session2, "custom2");468 // Refresh method must be invoked once.469 assert.ok(refreshSession.calledOnce);470 // The refresh method must recieve:471 var args = refreshSession.getCall(0).args;472 assert.equal(args[0], session);473 done();474 });475 }, 20);476 });477 });478 it("should return data from cache if auth token is not expired", function (done) {479 var c = new Connector(opts);480 createSession.onCall(0).callsArgWith(1, null, "custom", new Date(new Date().getTime() + 5000));481 c.getSession({ username: "mike" }, function (err, session, auth) {482 assert.ok(createSession.calledOnce);483 assert.ok(!err);484 assert.ok(auth);485 assert.equal(session, "custom");486 c.getSession({ auth: auth }, function (err, session2, auth2) {487 assert.ok(!refreshSession.hcalled);488 assert.ok(!err);489 assert.equal(session, session2);490 assert.equal(auth, auth2);491 done();492 });493 });494 });495 it("should fail when 'createSessionCb' callback returns a token expiration that is not of type Date.", function (done) {496 var c = new Connector(opts);497 createSession.onCall(0).callsArgWith(1, null, "custom", "invalid expiration time");498 c.getSession({ username: "mike" }, function (err, session, auth) {499 assert.ok(createSession.calledOnce);500 assert.ok(!session);501 assert.ok(!auth);502 assert.ok(err instanceof Error);503 assert.equal(err.message, "Create session aborted.");504 assert.equal(err.description, "When 'createSessionCb' callback returns an 'expire' argument. It must be of type Date.");505 done();506 });507 });508 it("should invoke 'createSessionCb' callback when 'refreshSessionCb' does not return a new session.", function (done) {509 var firstDate = new Date();510 var secondDate = new Date(firstDate.getTime() + 5000);511 // authenticates user and returns session and expiration 512 // firstDate is an expired time513 createSession.onCall(0).callsArgWith(1, null, "custom", firstDate);514 // authenticates user and returns sesison and expiration 515 createSession.onCall(1).callsArgWith(1, null, "custom2", secondDate);516 // refresh authentication does NOT return a new session517 refreshSession.onCall(0).callsArgWith(1, null, null);518 var c = new Connector(opts);519 // first getSession users520 c.getSession({ username: "mike", password: "1234" }, function (err, session, auth) {521 assert.ok(!err);522 assert.ok(auth);523 assert.equal(session, "custom");524 // wait until token expires525 setTimeout(function () {526 // token is expired, a new getSession must refresh the token527 c.getSession({ auth: auth }, function (err, session2, auth2) {528 assert.ok(!err);529 // auth token must remain the same one530 assert.equal(auth2, auth);531 // the session must be the new one532 assert.equal(session2, "custom2");533 // Refresh method must be invoked once.534 assert.ok(refreshSession.calledOnce);535 // Create method must be invoked twice.536 assert.ok(createSession.calledTwice);537 // The refresh method must recieve:538 var args = refreshSession.getCall(0).args;539 assert.equal(args[0], session);540 done();541 });542 }, 20);543 });544 });545 });546 describe("And module was initialized with a 'disposeSession' callback", function () {547 it("should invoke disposeSession when an item timeouts", function (done) {548 var timeout = 100;549 opts.config = { timeout: timeout };550 var c = new Connector(opts);551 createSession.onCall(0).callsArgWith(1, null, "custom");552 disposeSession.onCall(0).callsArg(1);553 c.getSession({ username: "mike" }, function (err, session, auth) {554 assert.ok(!err);555 assert.ok(auth);556 assert.equal(session, "custom");557 });558 setTimeout(function () {559 assert.ok(disposeSession.calledOnce);560 var args = disposeSession.getCall(0).args;561 assert.equal(args.length, 2);562 assert.equal(args[0], "custom");563 assert.equal(typeof args[1], "function");564 done();565 }, timeout + 20);566 });567 });568 });569 });570 describe("close", function () {571 beforeEach(function () {572 opts.credentialProps = ["username", "password"];573 opts.createSessionCb = createSession;574 opts.refreshSessionCb = refreshSession;575 opts.disposeSessionCb = disposeSession;576 });577 it("should no fail if there aren't any session.", function (done) {578 var c = new Connector(opts);579 c.close(done);580 });581 it("should no fail if caching is disabled.", function (done) {582 opts.disableCache = true;583 var c = new Connector(opts);584 c.close(done);585 });586 it("should invoke 'disposeSession' callback for each session", function (done) {587 var c = new Connector(opts);588 createSession.onCall(0).callsArgWith(1, null, "custom");589 createSession.onCall(1).callsArgWith(1, null, "custom2");590 disposeSession.onCall(0).callsArgWith(1);591 disposeSession.onCall(1).callsArgWith(1);592 c.getSession({ username: "mike" }, function (err, session, auth) {593 assert.ok(createSession.calledOnce);594 assert.ok(!err);595 assert.equal(session, "custom");596 assert.ok(auth);597 c.getSession({ username: "john" }, function (err, session2, auth2) {598 assert.ok(createSession.calledTwice);599 assert.ok(!err);600 assert.equal(session2, "custom2");601 assert.ok(auth2);602 c.close(function () {603 assert.ok(disposeSession.calledTwice);604 assert.equal(disposeSession.getCall(0).args[0], session);605 assert.equal(disposeSession.getCall(1).args[0], session2);606 done();607 });608 });609 });610 });611 });612 });613 describe("after module was initialized without disposeSession", function () {614 var createSession = sinon.stub();615 var disposeSession = sinon.stub();616 var refreshSession = sinon.stub();617 var opts;618 before(function () {619 require.uncache("../index.js");620 connector = require("../index.js");621 Connector = connector.Connector;622 connector.init("test", winston);623 });624 beforeEach(function () {625 createSession.reset();626 disposeSession.reset();627 refreshSession.reset();628 opts = {629 credentialProps: ["username", "password"],630 createSessionCb: createSession,631 refreshSessionCb: refreshSession632 };633 });634 describe("getSession", function () {635 describe("When a user has an existing session.", function () {636 it("should not fail when a cache item expires by timeout", function (done) {637 var expectedAuth = null;638 var timeout = 100;639 opts.config = { timeout: timeout };640 var c = new Connector(opts);641 createSession.onCall(0).callsArgWith(1, null, "custom");642 createSession.onCall(1).callsArgWith(1, null, "custom");643 c.getSession({ username: "mike" }, function (err, session, auth) {644 assert.ok(!err);645 assert.ok(auth);646 assert.equal(session, "custom");647 expectedAuth = auth;648 });649 setTimeout(function () {650 // getSession again651 c.getSession({ username: "mike" }, function (err, session2, auth2) {652 assert.ok(!err);653 assert.equal(session2, "custom");654 assert.ok(expectedAuth !== auth2);655 done();656 });657 }, timeout + 20);658 });659 });660 });661 describe("close", function () {662 it("should not fail", function (done) {663 var c = new Connector(opts);664 createSession.onCall(0).callsArgWith(1, null, "custom");665 c.getSession({ username: "mike" }, function (err, session, auth) {666 assert.ok(createSession.calledOnce);667 assert.ok(!err);668 assert.equal(session, "custom");669 assert.ok(auth);670 c.close(function () {671 assert.ok(!disposeSession.called);672 done();673 });674 });675 });676 it("should not fail when caching is disabled", function (done) {677 opts.disableCache = true;678 var c = new Connector(opts);679 createSession.onCall(0).callsArgWith(1, null, { auth: "custom" });680 c.getSession({ username: "mike" }, function (err, session, auth) {681 assert.ok(createSession.calledOnce);682 assert.ok(!err);683 assert.equal(session.auth, "custom");684 assert.equal(auth, "custom");685 c.close(function () {686 assert.ok(disposeSession.notCalled);687 done();688 });689 });690 });691 });692 });693 describe("after module was initialized without refreshSession", function () {694 var createSession = sinon.stub();695 var disposeSession = sinon.stub();696 var refreshSession = sinon.stub();697 var opts = {};698 before(function () {699 require.uncache("../index.js");700 connector = require("../index.js");701 Connector = connector.Connector;702 connector.init("test", winston);703 });704 beforeEach(function () {705 createSession.reset();706 disposeSession.reset();707 refreshSession.reset();708 opts = {709 credentialProps: ["username", "password"],710 createSessionCb: createSession,711 disposeSessionCb: disposeSession712 };713 });714 describe("getSession", function () {715 describe("When a user has an existing session.", function () {716 it("should fail when 'createSessionCb' callback returns a token's expiration.", function (done) {717 var c = new Connector(opts);718 createSession.onCall(0).callsArgWith(1, null, "custom", new Date(new Date().getTime() + 5000));719 c.getSession({ username: "mike" }, function (err, session, auth) {720 assert.ok(createSession.calledOnce);721 assert.ok(!auth);722 assert.ok(!session);723 assert.ok(err instanceof Error);724 assert.equal(err.message, "Create session aborted.");725 assert.equal(err.description, "When 'createSessionCb' callback returned an 'expire' argument but not 'refreshSessionCb' callback was initialized.");726 done();727 });728 });729 });730 });731 });732 });733 describe("init", function () {734 var dir = path.resolve(process.cwd(), "./logs/");735 beforeEach(function () {736 if (fs.existsSync(dir)) fs.rmdirSync(dir);737 });738 it("should fail if no label", function () {739 try {740 require.uncache("../index.js");741 connector = require("../index.js");742 Connector = connector.Connector;743 connector.init();744 assert.fail("should not reach here!");745 } catch (e) {746 assert.ok(e instanceof Error);747 assert.equal(e.message, "'label' argument is missing.");748 }749 });750 it("should fail if no winston", function () {751 try {752 require.uncache("../index.js");753 connector = require("../index.js");754 Connector = connector.Connector;755 connector.init("foo");756 assert.fail("should not reach here!");757 } catch (e) {758 assert.ok(e instanceof Error);759 assert.equal(e.message, "'winston' argument is missing.");760 }761 });762 it("should work", function () {763 require.uncache("../index.js");764 connector = require("../index.js");765 Connector = connector.Connector;766 connector.init("test", winston, noop);767 });768 it("should fail when is initialized by a second time", function () {769 require.uncache("../index.js");770 connector = require("../index.js");771 Connector = connector.Connector;772 connector.init("test", winston, noop);773 try {774 connector.init("test", winston, noop);775 assert.fail("Did not fail.");776 } catch (e) {777 assert.ok(e instanceof Error);778 assert.equal(e.message, "Can't be initialized twice.");779 }780 });781 it("should work with --level", function () {782 require.uncache("../index.js");783 process.argv.push("--level");784 process.argv.push("debug");785 connector = require("../index.js");786 connector.init("test", winston, noop);787 });788 it("'timestamp' winston option must be a valid function.", function () {789 require.uncache("../index.js");790 process.argv.push("--level");791 process.argv.push("debug");792 connector = require("../index.js");793 connector.init("test", winston);794 assert.ok(winston.add.calledTwice);795 var args = winston.add.getCall(0).args;796 var timestamp = args[1].timestamp;797 assert.equal(typeof timestamp, "function");798 assert.ok(timestamp());799 });800 it("should create log folder.", function () {801 require.uncache("../index.js");802 process.argv.push("--level");803 process.argv.push("debug");804 connector = require("../index.js");805 connector.init("test", winston);806 assert.ok(fs.existsSync(dir));807 });808 it("should not fail id log folder aready exists.", function () {809 fs.mkdirSync(dir);810 assert.ok(fs.existsSync(dir));811 require.uncache("../index.js");812 process.argv.push("--level");813 process.argv.push("debug");814 connector = require("../index.js");815 connector.init("test", winston);816 assert.ok(fs.existsSync(dir));817 });818 });819 describe("isHostAllowed", function () {820 before(function () {821 process.env.RUNNING_ON = "hub";822 connector = require("../index.js");823 });824 it("Should fail with no host", function (done) {825 connector.isHostAllowed(function (err, allowed) {826 assert.ok(!allowed);827 assert.ok(err);828 assert.strictEqual(err.message, "host parameter is mandatory");829 done();830 });831 });832 it("Should fail with invalid host type", function (done) {833 connector.isHostAllowed(123, function (err, allowed) {834 assert.ok(!allowed);835 assert.ok(err);836 assert.strictEqual(err.message, "host must be a string");837 done();838 });839 });840 it("Should fail with missing cb host type", function (done) {841 connector.isHostAllowed(123, function (err, allowed) {842 assert.ok(!allowed);843 assert.ok(err);844 assert.strictEqual(err.message, "host must be a string");845 done();846 });847 });848 it("Should fail with invalid host", function (done) {849 connector.isHostAllowed("INVALID", function (err, allowed) {850 assert.ok(!allowed);851 assert.ok(err);852 assert.strictEqual(err.message, "getaddrinfo ENOTFOUND");853 done();854 });855 });856 it("Should return invalid with loopback host ipv4", function (done) {857 connector.isHostAllowed("localhost", function (err, allowed) {858 assert.ok(!err);859 assert.ok(!allowed);860 done();861 });862 });863 it("Should return invalid with loopback ip ipv4", function (done) {864 connector.isHostAllowed("127.0.0.3", function (err, allowed) {865 assert.ok(!err);866 assert.ok(!allowed);867 done();868 });869 });870 it("Should return invalid with loopback host ipv6", function (done) {871 connector.isHostAllowed("::1", function (err, allowed) {872 assert.ok(!err);873 assert.ok(!allowed);874 done();875 });876 });877 it("Should return invalid with internal host ipv4", function (done) {878 connector.isHostAllowed("10.0.1.10", function (err, allowed) {879 assert.ok(!err);880 assert.ok(!allowed);881 done();882 });883 });884 it("Should return invalid with internal host ipv6", function (done) {885 connector.isHostAllowed("fe80::6267:20ff:fe22:4928", function (err, allowed) {886 assert.ok(!err);887 assert.ok(!allowed);888 done();889 });890 });891 it("Should work with valid hostname", function (done) {892 connector.isHostAllowed("www.google.com", function (err, allowed) {893 assert.ok(!err);894 assert.ok(allowed);895 done();896 });897 });898 it("Should work with valid IP", function (done) {899 connector.isHostAllowed("64.233.186.147", function (err, allowed) {900 assert.ok(!err);901 assert.ok(allowed);902 done();903 });904 });905 it("Should work when not running on hub", function (done) {906 process.env.RUNNING_ON = "agent";907 connector.isHostAllowed("localhost", function (err, allowed) {908 assert.ok(!err);909 assert.ok(allowed);910 process.env.RUNNING_ON = "hub";911 done();912 });913 });914 });915});916/**917 * Removes a module from the cache918 */919require.uncache = function (moduleName) {920 // Run over the cache looking for the files921 // loaded by the specified module name922 require.searchCache(moduleName, function (mod) {923 delete require.cache[mod.id];924 });925};926/**927 * Runs over the cache to search for all the cached928 * files929 */930require.searchCache = function (moduleName, callback) {931 // Resolve the module identified by the specified name932 var mod = require.resolve(moduleName);933 // Check if the module has been resolved and found within934 // the cache935 if (mod && ((mod = require.cache[mod]) !== undefined)) {936 // Recursively go over the results937 (function run(mod) {938 // Go over each of the module's children and939 // run over it940 mod.children.forEach(function (child) {941 run(child);942 });943 // Call the specified callback providing the944 // found module945 callback(mod);946 })(mod);947 }...
syntax-mediakeysession.js
Source:syntax-mediakeysession.js
...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.');...
session.js
Source:session.js
...7 }8 describe('Creation', function () {9 it('should not throw error when create with empty data', function () {10 assert.doesNotThrow(function () {11 createSession();12 });13 });14 });15 describe('Get/Set methods', function () {16 [17 {18 field: 'Id',19 value: 'id1'20 },21 {22 field: 'Section',23 value: 's1'24 },25 {26 field: 'CollectApp',27 value: 'rest'28 }29 ].forEach(function (test) {30 it('should set/get "' + test.field + '"', function () {31 var sess = createSession(),32 getter = 'get' + test.field,33 setter = 'set' + test.field;34 assert.notEqual(sess[getter](), test.value);35 sess[setter](test.value);36 assert.equal(sess[getter](), test.value);37 });38 });39 it('should get/set "CreatedAt"', function () {40 var sess = createSession(),41 date = new Date(),42 ts = 123456789;43 sess.setCreatedAt(ts);44 assert.equal(sess.getCreatedAt(), ts, 'Check correct setting timestamp');45 sess.setCreatedAt(date);46 assert.equal(sess.getCreatedAt(), +date, 'Check correct setting Date');47 });48 it('should get/set "Data"', function () {49 var sess = createSession();50 assert.deepEqual(sess.getData(), {}, 'Check init value');51 sess.setData();52 assert.deepEqual(sess.getData(), {}, 'Check settings empty value');53 sess.setData({54 test: 123,55 foo: 'bar'56 });57 assert.deepEqual(sess.getData(), {58 test: 123,59 foo: 'bar'60 }, 'Check correct setting');61 sess.setData({62 test: 123456789,63 my: 'cat'64 });65 assert.deepEqual(sess.getData(), {66 test: 123456789,67 foo: 'bar',68 my: 'cat'69 }, 'Check correct merging');70 });71 it('should get/set "Data value"', function () {72 var sess = createSession();73 assert.equal(sess.getDataValue('val'), null);74 sess.setDataValue('val', 0);75 assert.equal(sess.getDataValue('val'), 0);76 sess.setDataValue('val', 'qwe');77 assert.equal(sess.getDataValue('val'), 'qwe');78 });79 it('should get "ModifiedAt"', function () {80 var sess = createSession({createdAt: 123456789});81 assert.equal(sess.getModifiedAt(), 123456789);82 });83 });84 describe('Events', function () {85 it('should create session with Events', function () {86 var sess = createSession({87 section: 'section',88 events: [{definitionId: 'defId'}]89 });90 var events = sess.getEvents();91 assert.equal(events.length, 1);92 assert(events[0] instanceof Profile.Event);93 });94 it('should add event to session', function () {95 var sess = createSession(),96 event = sess.addEvent({definitionId: 'test'}),97 events = sess.getEvents();98 assert(event instanceof Profile.Event);99 assert.equal(events.length, 1);100 assert(events[0] instanceof Profile.Event);101 });102 it('should throw error on existing event', function () {103 var sess = createSession({104 events: [{105 id: '123',106 definitionId: 'old-def'107 }]108 }),109 event = new Profile.Event({110 id: '123',111 definitionId: 'new-def'112 }),113 events = sess.getEvents();114 assert.equal(events.length, 1);115 assert.equal(events[0].getDefinitionId(), 'old-def');116 assert['throws'](function () {117 sess.addEvent(event);118 }, /Event with id "123" already exists/);119 });120 it('Should throw error on invalid event', function () {121 var sess = createSession();122 assert['throws'](function () {123 sess.addEvent();124 });125 });126 it('Should get event by id', function () {127 var event,128 sess = createSession({129 events: [{130 id: '123',131 definitionId: 'defId'132 }]133 });134 event = sess.getEvent('none');135 assert.equal(event, null);136 event = sess.getEvent('123');137 assert.equal(event.getDefinitionId(), 'defId');138 });139 it('should get events', function () {140 var sess = createSession();141 var events = sess.getEvents();142 assert.equal(events.length, 0);143 sess.addEvent({definitionId: 'defId-123'});144 sess.addEvent({definitionId: 'defId-234'});145 events = sess.getEvents();146 assert.equal(events.length, 2);147 assert.equal(events[0].getDefinitionId(), 'defId-123');148 assert.equal(events[1].getDefinitionId(), 'defId-234');149 events = sess.getEvents('defId-123');150 assert.equal(events.length, 1);151 assert.equal(events[0].getDefinitionId(), 'defId-123');152 });153 it('should test backref of events', function () {154 var sess = createSession(),155 event = sess.addEvent({definitionId: 'test'}),156 events = sess.getEvents();157 assert.equal(events[0].getDefinitionId(), 'test');158 event.setDefinitionId('defId');159 assert.equal(events[0].getDefinitionId(), 'defId');160 });161 it('should sort events', function () {162 var session = createSession({163 events: [{164 id: 'ev1',165 createdAt: 10166 }, {167 id: 'ev2',168 createdAt: 5169 }]170 }),171 events;172 events = session.getEvents();173 assert.equal(events[0].getId(), 'ev1');174 assert.equal(events[1].getId(), 'ev2');175 events = session.sortEvents().getEvents();176 assert.equal(events[0].getId(), 'ev2');177 assert.equal(events[1].getId(), 'ev1');178 });179 it('should return null if there os no last event', function () {180 var sess = createSession();181 assert.strictEqual(sess.getLastEvent(), null);182 });183 it('should return last event from sesson', function () {184 var session = createSession({185 events: [{186 id: 'ev1',187 createdAt: 10188 }, {189 id: 'ev2',190 createdAt: 5191 }]192 });193 assert.strictEqual(session.getLastEvent().getId(), 'ev2');194 });195 });196 describe('Serialization', function () {197 it('should serialize session', function () {198 var sess = createSession({199 id: '123456',200 section: 'foo',201 collectApp: 'rest',202 createdAt: 123,203 data: {key: 'value'}204 });205 assert.deepEqual(sess.serialize(), {206 id: '123456',207 section: 'foo',208 collectApp: 'rest',209 createdAt: 123,210 events: [],211 data: {key: 'value'}212 });213 });214 it('should serialize data', function () {215 var rawData = {216 id: 'qwe',217 collectApp: 'app',218 section: 'sec',219 createdAt: 1,220 data: {test: 'cool'},221 events: [{222 id: 'ev1',223 definitionId: 'defId',224 createdAt: 3,225 data: {foo: 'bar'}226 }]227 };228 var session = createSession(rawData);229 assert.deepEqual(session.serialize(), rawData);230 });231 describe('Partially serialization', function () {232 var rawData = {233 id: 'qwe',234 collectApp: 'app',235 section: 'sec',236 createdAt: 1,237 data: {test: 'cool'},238 events: [{239 id: 'ev1',240 definitionId: 'defId',241 createdAt: 3,242 data: {foo: 'bar'}243 }]244 };245 it('should collect only common props if no data or event(s) changed', function () {246 var session = createSession(rawData);247 session.resetDirty();248 assert.deepEqual(session.serialize(true), {249 id: 'qwe',250 collectApp: 'app',251 section: 'sec',252 createdAt: 1,253 data: {},254 events: []255 });256 });257 it('should collect common props and changed data', function () {258 var session = createSession(rawData);259 session.resetDirty();260 session.setDataValue('a', 1);261 assert.deepEqual(session.serialize(true), {262 id: 'qwe',263 collectApp: 'app',264 section: 'sec',265 createdAt: 1,266 data: {267 a: 1,268 test: 'cool'269 },270 events: []271 });272 });273 it('should collect common props and changed event', function () {274 var session = createSession(rawData);275 session.resetDirty();276 session.getLastEvent().setData({b: 0});277 assert.deepEqual(session.serialize(true), {278 id: 'qwe',279 collectApp: 'app',280 section: 'sec',281 createdAt: 1,282 data: {},283 events: [{284 id: 'ev1',285 definitionId: 'defId',286 createdAt: 3,287 data: {288 b: 0,289 foo: 'bar'290 }291 }]292 });293 });294 });295 });296 describe('Validation', function () {297 it('should be valid if all required fields exist', function () {298 var sess = createSession({299 id: 'sid',300 collectApp: 'app',301 section: 'section'302 });303 assert(sess.isValid());304 });305 [306 'Id', 'Section', 'CollectApp', 'CreatedAt'307 ].forEach(function (field) {308 it('should be invalid if required field "' + field + '" not defined', function () {309 var event = createSession({310 id: 'sid',311 collectApp: 'app',312 section: 'section'313 });314 assert(event.isValid());315 event['set' + field](null);316 assert.equal(event.isValid(), false);317 });318 });319 });320 describe('Merging', function () {321 it('should throw error if session is not instance of Session', function () {322 var fakeSession = {id: 1},323 session = createSession();324 assert['throws'](function () {325 session.merge(fakeSession);326 }, /Argument "session" should be a Session instance/);327 });328 it('should throw error if ids are different', function () {329 var session1 = createSession({id: '1'}),330 session2 = createSession({id: '2'});331 assert['throws'](function () {332 session1.merge(session2);333 }, /Session IDs should be similar/);334 });335 it('should properly merge session to other one', function () {336 var session1 = createSession({337 id: '1',338 data: {339 name: 'value',340 a: 1341 },342 events: [{id: 'ev1'}]343 }),344 session2 = createSession({345 id: '1',346 data: {347 name: 'new',348 b: 2349 },350 events: [{id: 'ev1'}, {id: 'ev2'}]351 });352 session1.merge(session2);353 assert.strictEqual(session1.getId(), '1');354 assert.deepEqual(session1.getData(), {355 name: 'new',356 a: 1,357 b: 2358 });359 assert.strictEqual(session1.getEvents().length, 2);360 });361 });362 describe('Dirty flag', function () {363 it('should be marked as dirty after creation', function () {364 var session = createSession();365 assert(session.hasChanges());366 });367 it('should be marked as not dirty', function () {368 var session = createSession();369 session.resetDirty();370 assert.equal(session.hasChanges(), false);371 });372 [373 {374 field: 'Id',375 value: 'id1'376 },377 {378 field: 'Section',379 value: 's1'380 },381 {382 field: 'CollectApp',383 value: 'rest'384 },385 {386 field: 'CreatedAt',387 value: new Date()388 },389 {390 field: 'Data',391 value: {a: 1}392 }393 ].forEach(function (test) {394 it('should be marked as dirty after set "' + test.field + '"', function () {395 var session = createSession(),396 setter = 'set' + test.field;397 session.resetDirty();398 session[setter](test.value);399 assert(session.hasChanges());400 });401 });402 it('should be marked as dirty after set DataValue', function () {403 var session = createSession();404 session.resetDirty();405 session.setDataValue('a', {b: 321});406 assert(session.hasChanges());407 });408 it('should be marked as dirty if some of events has changed flag', function () {409 var session = createSession(),410 event = session.createEvent({411 id: '1',412 definitionId: '2'413 });414 session.resetDirty();415 session.addEvent(event);416 assert(session.hasChanges());417 session.resetDirty();418 assert.equal(session.hasChanges(), false);419 event.setData({q: 0});420 assert(session.hasChanges());421 });422 });423});
driver-specs.js
Source:driver-specs.js
...39 it('should call inner driver\'s createSession with desired capabilities', async function () {40 mockFakeDriver.expects("createSession")41 .once().withExactArgs(BASE_CAPS, undefined, null, [])42 .returns([SESSION_ID, BASE_CAPS]);43 await appium.createSession(BASE_CAPS);44 mockFakeDriver.verify();45 });46 it('should call inner driver\'s createSession with desired and default capabilities', async function () {47 let defaultCaps = {deviceName: 'Emulator'}48 , allCaps = _.extend(_.clone(defaultCaps), BASE_CAPS);49 appium.args.defaultCapabilities = defaultCaps;50 mockFakeDriver.expects("createSession")51 .once().withArgs(allCaps)52 .returns([SESSION_ID, allCaps]);53 await appium.createSession(BASE_CAPS);54 mockFakeDriver.verify();55 });56 it('should call inner driver\'s createSession with desired and default capabilities without overriding caps', async function () {57 // a default capability with the same key as a desired capability58 // should do nothing59 let defaultCaps = {platformName: 'Ersatz'};60 appium.args.defaultCapabilities = defaultCaps;61 mockFakeDriver.expects("createSession")62 .once().withArgs(BASE_CAPS)63 .returns([SESSION_ID, BASE_CAPS]);64 await appium.createSession(BASE_CAPS);65 mockFakeDriver.verify();66 });67 it('should kill all other sessions if sessionOverride is on', async function () {68 appium.args.sessionOverride = true;69 // mock three sessions that should be removed when the new one is created70 let fakeDrivers = [new FakeDriver(),71 new FakeDriver(),72 new FakeDriver()];73 let mockFakeDrivers = _.map(fakeDrivers, (fd) => {return sinon.mock(fd);});74 mockFakeDrivers[0].expects('deleteSession')75 .once();76 mockFakeDrivers[1].expects('deleteSession')77 .once()78 .throws('Cannot shut down Android driver; it has already shut down');79 mockFakeDrivers[2].expects('deleteSession')80 .once();81 appium.sessions['abc-123-xyz'] = fakeDrivers[0];82 appium.sessions['xyz-321-abc'] = fakeDrivers[1];83 appium.sessions['123-abc-xyz'] = fakeDrivers[2];84 let sessions = await appium.getSessions();85 sessions.should.have.length(3);86 mockFakeDriver.expects("createSession")87 .once().withExactArgs(BASE_CAPS, undefined, null, [])88 .returns([SESSION_ID, BASE_CAPS]);89 await appium.createSession(BASE_CAPS);90 sessions = await appium.getSessions();91 sessions.should.have.length(1);92 for (let mfd of mockFakeDrivers) {93 mfd.verify();94 }95 mockFakeDriver.verify();96 });97 it('should call "createSession" with W3C capabilities argument, if provided', async function () {98 mockFakeDriver.expects("createSession")99 .once().withArgs(null, undefined, W3C_CAPS)100 .returns([SESSION_ID, BASE_CAPS]);101 await appium.createSession(undefined, undefined, W3C_CAPS);102 mockFakeDriver.verify();103 });104 it('should call "createSession" with W3C capabilities argument with additional provided parameters', async function () {105 let w3cCaps = {106 ...W3C_CAPS,107 alwaysMatch: {108 ...W3C_CAPS.alwaysMatch,109 'appium:someOtherParm': 'someOtherParm',110 },111 };112 mockFakeDriver.expects("createSession")113 .once().withArgs(null, undefined, {114 alwaysMatch: {115 ...w3cCaps.alwaysMatch,116 'appium:someOtherParm': 'someOtherParm',117 },118 firstMatch: [{}],119 })120 .returns([SESSION_ID, insertAppiumPrefixes(BASE_CAPS)]);121 await appium.createSession(undefined, undefined, w3cCaps);122 mockFakeDriver.verify();123 });124 it('should call "createSession" with JSONWP capabilities if W3C has incomplete capabilities', async function () {125 let w3cCaps = {126 ...W3C_CAPS,127 alwaysMatch: {128 ...W3C_CAPS.alwaysMatch,129 'appium:someOtherParm': 'someOtherParm',130 },131 };132 let jsonwpCaps = {133 ...BASE_CAPS,134 automationName: 'Fake',135 someOtherParam: 'someOtherParam',136 };137 mockFakeDriver.expects("createSession")138 .once().withArgs(jsonwpCaps, undefined, null)139 .returns([SESSION_ID, jsonwpCaps]);140 await appium.createSession(jsonwpCaps, undefined, w3cCaps);141 mockFakeDriver.verify();142 });143 });144 describe('deleteSession', function () {145 let appium;146 let mockFakeDriver;147 beforeEach(function () {148 [appium, mockFakeDriver] = getDriverAndFakeDriver();149 });150 afterEach(function () {151 mockFakeDriver.restore();152 });153 it('should remove the session if it is found', async function () {154 let [sessionId] = (await appium.createSession(BASE_CAPS)).value;155 let sessions = await appium.getSessions();156 sessions.should.have.length(1);157 await appium.deleteSession(sessionId);158 sessions = await appium.getSessions();159 sessions.should.have.length(0);160 });161 it('should call inner driver\'s deleteSession method', async function () {162 const [sessionId] = (await appium.createSession(BASE_CAPS)).value;163 mockFakeDriver.expects("deleteSession")164 .once().withExactArgs(sessionId, [])165 .returns();166 await appium.deleteSession(sessionId);167 mockFakeDriver.verify();168 // cleanup, since we faked the delete session call169 await mockFakeDriver.object.deleteSession();170 });171 });172 describe('getSessions', function () {173 let appium;174 let sessions;175 before(function () {176 appium = new AppiumDriver({});177 });178 afterEach(async function () {179 for (let session of sessions) {180 await appium.deleteSession(session.id);181 }182 });183 it('should return an empty array of sessions', async function () {184 sessions = await appium.getSessions();185 sessions.should.be.an.array;186 sessions.should.be.empty;187 });188 it('should return sessions created', async function () {189 let session1 = (await appium.createSession(_.extend(_.clone(BASE_CAPS), {cap: 'value'}))).value;190 let session2 = (await appium.createSession(_.extend(_.clone(BASE_CAPS), {cap: 'other value'}))).value;191 sessions = await appium.getSessions();192 sessions.should.be.an.array;193 sessions.should.have.length(2);194 sessions[0].id.should.equal(session1[0]);195 sessions[0].capabilities.should.eql(session1[1]);196 sessions[1].id.should.equal(session2[0]);197 sessions[1].capabilities.should.eql(session2[1]);198 });199 });200 describe('getStatus', function () {201 let appium;202 before(function () {203 appium = new AppiumDriver({});204 });205 it('should return a status', async function () {206 let status = await appium.getStatus();207 status.build.should.exist;208 status.build.version.should.exist;209 });210 });211 describe('sessionExists', function () {212 });213 describe('attachUnexpectedShutdownHandler', function () {214 let appium215 , mockFakeDriver;216 beforeEach(function () {217 [appium, mockFakeDriver] = getDriverAndFakeDriver();218 });219 afterEach(async function () {220 await mockFakeDriver.object.deleteSession();221 mockFakeDriver.restore();222 appium.args.defaultCapabilities = {};223 });224 it('should remove session if inner driver unexpectedly exits with an error', async function () {225 let [sessionId,] = (await appium.createSession(_.clone(BASE_CAPS))).value; // eslint-disable-line comma-spacing226 _.keys(appium.sessions).should.contain(sessionId);227 appium.sessions[sessionId].unexpectedShutdownDeferred.reject(new Error("Oops"));228 // let event loop spin so rejection is handled229 await sleep(1);230 _.keys(appium.sessions).should.not.contain(sessionId);231 });232 it('should remove session if inner driver unexpectedly exits with no error', async function () {233 let [sessionId,] = (await appium.createSession(_.clone(BASE_CAPS))).value; // eslint-disable-line comma-spacing234 _.keys(appium.sessions).should.contain(sessionId);235 appium.sessions[sessionId].unexpectedShutdownDeferred.resolve();236 // let event loop spin so rejection is handled237 await sleep(1);238 _.keys(appium.sessions).should.not.contain(sessionId);239 });240 it('should not remove session if inner driver cancels unexpected exit', async function () {241 let [sessionId,] = (await appium.createSession(_.clone(BASE_CAPS))).value; // eslint-disable-line comma-spacing242 _.keys(appium.sessions).should.contain(sessionId);243 appium.sessions[sessionId].onUnexpectedShutdown.cancel();244 // let event loop spin so rejection is handled245 await sleep(1);246 _.keys(appium.sessions).should.contain(sessionId);247 });248 });249 describe('getDriverForCaps', function () {250 it('should not blow up if user does not provide platformName', function () {251 let appium = new AppiumDriver({});252 (() => { appium.getDriverForCaps({}); }).should.throw(/platformName/);253 });254 it('should get XCUITestDriver driver for automationName of XCUITest', function () {255 let appium = new AppiumDriver({});...
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
...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
...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
...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 });...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 for (const browserType of BROWSER) {4 const browser = await playwright[browserType].launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 const session = await page.context().newCDPSession(page);8 const { sessionId } = session;9 console.log(sessionId);10 await page.waitForLoadState('load');11 await browser.close();12 }13})();14const playwright = require('playwright');15(async () => {16 for (const browserType of BROWSER) {17 const browser = await playwright[browserType].launch({ headless: false });18 const context = await browser.newContext();19 const page = await context.newPage();20 const session = await page.context().newCDPSession(page);21 const { sessionId } = session;22 const newSession = await context.browser().connectToSession(sessionId);23 await page.waitForLoadState('load');24 await browser.close();25 }26})();27const playwright = require('playwright');28(async () => {29 for (const browserType of BROWSER) {30 const browser = await playwright[browserType].launch({ headless: false });31 const context = await browser.newContext();32 const page = await context.newPage();33 const session = await page.context().newCDPSession(page);34 const { sessionId } = session;35 const newSession = await context.browser().connectToSession(sessionId);36 await newSession.send('Target
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright['chromium'].launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const session = await page.context().newCDPSession(page);7 await session.send('Page.enable');8 await session.send('Page.loadEventFired');9 const cookies = await session.send('Network.getAllCookies');10 console.log(cookies);11 await browser.close();12})();13### `createSession(page: Page): Promise<CDPSession>`
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 const session = await context._createSession();7 await session.send('Input.dispatchKeyEvent', {8 });9 await session.send('Input.dispatchKeyEvent', {10 });11})();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await context.close();7 await browser.close();8})();9const playwright = require('playwright');10(async () => {11 const browser = await playwright.chromium.launch({ headless: false });12 const context = await browser.newContext();13 const page = await context.newPage();14 await context.close();15 await browser.close();16})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const session = await context.newCDPSession(page);7 await session.send('Page.enable');8 await session.send('Page.captureScreenshot', { format: 'png' });9 await browser.close();10})();11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await page.screenshot({ path: 'example.png' });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.screenshot({ path: 'example.png' });25 await browser.close();26})();27const { chromium } = require('playwright');28(async () => {29 const browser = await chromium.launch();30 const context = await browser.newContext();31 const page = await context.newPage();32 await page.screenshot({ path: 'example.png' });33 await browser.close();34})();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.chromium.launch({ headless: false });4 const context = await browser.newContext({5 });6 const page = await context.newPage();7 await page.waitForTimeout(5000);8 await context.close();9 await browser.close();10})();
Using AI Code Generation
1const { chromium } = require('playwright');2const { createSession } = require('playwright/lib/server/chromium/crBrowser');3const { chromiumLauncher } = require('playwright/lib/server/chromium/chromiumLauncher');4(async () => {5 const browser = await chromium.launch({6 });7 const browserWSEndpoint = browser.wsEndpoint();8 const browserContext = await browser.newContext();9 const page = await browserContext.newPage();10 const { session, transport } = await createSession(11 );12 console.log('session', session);13 console.log('transport', transport);14 await page.waitForNavigation();15 await page.waitForNavigation();16 await page.goBack();17 await page.waitForNavigation();18 await page.goForward();19 await page.waitForNavigation();20 await page.reload();21 await page.waitForNavigation();22 await page.close();23 await browser.close();24})();
Using AI Code Generation
1const playwright = require('playwright');2const { createSession } = require('playwright/lib/server/chromium/crConnection.js');3const browser = await playwright.chromium.launch();4const page = await browser.newPage();5const session = await createSession(page, 'Page.navigate', {6});7console.log(session);8await browser.close();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!