Best JavaScript code snippet using playwright-internal
AppVariantFactory.qunit.js
Source:AppVariantFactory.qunit.js
...37 var fnNewConnectorCall = sandbox.stub(WriteUtils, "sendRequest");38 fnNewConnectorCall.onFirstCall().resolves({response: '{ "id": "id.string", "reference":"base.id", "content": [] }'});39 fnNewConnectorCall.onSecondCall().resolves({response: '{ "id": "id.json", "reference":"base.id", "content": [] }'});40 fnNewConnectorCall.onThirdCall().resolves({response: '{ "id": "id.refVer", "reference":"base.id", "referenceVersion":"1.1", "content": [] }'});41 return AppVariantFactory.prepareUpdate({42 id: "id.string"43 }).then(function(oVariant) {44 assert.equal(oVariant.getDefinition().id, "id.string");45 assert.equal(oVariant.getDefinition().reference, "base.id");46 assert.ok(!oVariant.getDefinition().referenceVersion);47 }).then(function() {48 return AppVariantFactory.prepareUpdate({49 id: "id.json"50 });51 }).then(function(oVariant) {52 assert.equal(oVariant.getDefinition().id, "id.json");53 assert.equal(oVariant.getDefinition().reference, "base.id");54 assert.ok(!oVariant.getDefinition().referenceVersion);55 }).then(function() {56 return AppVariantFactory.prepareUpdate({57 id: "id.refVer"58 });59 }).then(function(oVariant) {60 assert.equal(oVariant.getDefinition().id, "id.refVer");61 assert.equal(oVariant.getDefinition().reference, "base.id");62 assert.equal(oVariant.getDefinition().referenceVersion, "1.1");63 });64 });65 QUnit.test("When prepareUpdate is called only once", function(assert) {66 sandbox.stub(WriteUtils, "sendRequest").resolves({67 response: JSON.stringify({68 id: "a.id",69 reference: "a.reference"70 })71 });72 return AppVariantFactory.prepareUpdate({73 id: "a.id"74 }).then(function(oVariant) {75 assert.notEqual(oVariant, null);76 assert.equal(oVariant.getDefinition().id, "a.id");77 assert.equal(oVariant.getDefinition().reference, "a.reference");78 assert.equal(oVariant.getMode(), "EXISTING");79 });80 });81 QUnit.test("When prepareUpdate is called and failure happens", function(assert) {82 sandbox.stub(WriteUtils, "sendRequest").rejects({message: "lalala"});83 return AppVariantFactory.prepareUpdate({84 id: "a.id"85 }).then(function() {86 assert.notOk("Should never succeed");87 }).catch(function(oError) {88 assert.ok(oError.message, "lalala");89 });90 });91 QUnit.test("When prepareUpdate is called and variant was saved as a local object", function(assert) {92 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({93 response: JSON.stringify({94 id: "a.id",95 reference: "a.reference",96 layer: "CUSTOMER",97 packageName: "$TMP"98 })99 });100 var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: ""});101 return AppVariantFactory.prepareUpdate({102 id: "a.id"103 }).then(function(oVariant) {104 return oVariant.submit();105 }).then(function(oResponse) {106 assert.ok(oStubOpenTransportSelection.calledOnce);107 assert.notEqual(oResponse, null);108 assert.equal(oNewConnectorStub.callCount, 2);109 assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id");110 assert.equal(oNewConnectorStub.getCall(0).args[1], "GET");111 assert.equal(oNewConnectorStub.getCall(1).args[0], "/sap/bc/lrep/appdescr_variants/a.id?sap-language=en");112 assert.equal(JSON.parse(oNewConnectorStub.getCall(1).args[2].payload).packageName, "$TMP");113 assert.equal(JSON.parse(oNewConnectorStub.getCall(1).args[2].payload).reference, "a.reference");114 assert.equal(JSON.parse(oNewConnectorStub.getCall(1).args[2].payload).id, "a.id");115 assert.equal(JSON.parse(oNewConnectorStub.getCall(1).args[2].payload).layer, "CUSTOMER");116 assert.equal(oNewConnectorStub.getCall(1).args[1], "PUT");117 });118 });119 QUnit.test("When prepareUpdate is called and variant was already published", function(assert) {120 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({121 response: JSON.stringify({122 id: "a.id",123 reference: "a.reference",124 layer: "CUSTOMER"125 })126 });127 var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: "aTransport"});128 return AppVariantFactory.prepareUpdate({129 id: "a.id"130 }).then(function(oVariant) {131 return oVariant.submit();132 }).then(function(oResponse) {133 assert.ok(oStubOpenTransportSelection.calledOnce);134 assert.notEqual(oResponse, null);135 assert.equal(oNewConnectorStub.callCount, 2);136 assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id");137 assert.equal(oNewConnectorStub.getCall(0).args[1], "GET");138 assert.equal(oNewConnectorStub.getCall(1).args[0], "/sap/bc/lrep/appdescr_variants/a.id?changelist=aTransport&sap-language=en");139 assert.equal(oNewConnectorStub.getCall(1).args[1], "PUT");140 });141 });142 QUnit.test("When prepareDelete is called", function(assert) {143 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({144 response: JSON.stringify({145 id: "a.id",146 reference: "a.reference",147 layer: "CUSTOMER"148 })149 });150 return AppVariantFactory.prepareDelete({151 id: "a.id"152 }).then(function(oVariant) {153 assert.notEqual(oVariant, null);154 assert.equal(oVariant.getDefinition().id, "a.id");155 assert.equal(oVariant.getDefinition().reference, "a.reference");156 assert.equal(oNewConnectorStub.callCount, 1);157 assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id");158 assert.equal(oNewConnectorStub.getCall(0).args[1], "GET");159 assert.equal(oVariant.getMode(), "DELETION");160 });161 });162 QUnit.test("Smart Business: When prepareDelete is called", function(assert) {163 return AppVariantFactory.prepareDelete({164 id: "a.id",165 isForSmartBusiness: true166 }).then(function(oVariant) {167 assert.notEqual(oVariant, null);168 assert.equal(oVariant.getDefinition().id, "a.id");169 assert.equal(oVariant.getMode(), "DELETION");170 });171 });172 QUnit.test("When prepareDelete is called to prepare a delete app variant config and submit is called to delete an app variant saved as local object", function(assert) {173 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({174 response: JSON.stringify({175 id: "a.id",176 reference: "a.reference",177 layer: "CUSTOMER",178 packageName: ""179 })180 });181 var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: ""});182 return AppVariantFactory.prepareDelete({183 id: "a.id"184 }).then(function(oVariant) {185 return oVariant.submit();186 }).then(function(oResponse) {187 assert.ok(oStubOpenTransportSelection.calledOnce);188 assert.notEqual(oResponse, null);189 assert.equal(oNewConnectorStub.callCount, 2);190 assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id");191 assert.equal(oNewConnectorStub.getCall(0).args[1], "GET");192 assert.equal(oNewConnectorStub.getCall(1).args[0], "/sap/bc/lrep/appdescr_variants/a.id");193 assert.equal(oNewConnectorStub.getCall(1).args[1], "DELETE");194 });195 });196 QUnit.test("When prepareDelete is called to prepare a delete app variant config and submit is called to delete a published app variant", function(assert) {197 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({198 response: JSON.stringify({199 id: "a.id",200 reference: "a.reference",201 layer: "CUSTOMER",202 packageName: ""203 })204 });205 var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: "aTransport"});206 return AppVariantFactory.prepareDelete({207 id: "a.id"208 }).then(function(oVariant) {209 return oVariant.submit();210 }).then(function(oResponse) {211 assert.ok(oStubOpenTransportSelection.calledOnce);212 assert.notEqual(oResponse, null);213 assert.equal(oNewConnectorStub.callCount, 2);214 assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id");215 assert.equal(oNewConnectorStub.getCall(0).args[1], "GET");216 assert.equal(oNewConnectorStub.getCall(1).args[0], "/sap/bc/lrep/appdescr_variants/a.id?changelist=aTransport");217 assert.equal(oNewConnectorStub.getCall(1).args[1], "DELETE");218 });219 });220 QUnit.test("Smart Business: When prepareDelete is called to prepare a delete app variant config and submit is called to delete a published app variant", function(assert) {221 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves();222 var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection");223 return AppVariantFactory.prepareDelete({224 id: "a.id",225 transport: "aTransport",226 isForSmartBusiness: true227 }).then(function(oVariant) {228 return oVariant.submit();229 }).then(function(oResponse) {230 assert.ok(oStubOpenTransportSelection.notCalled);231 assert.equal(oResponse, undefined);232 assert.equal(oNewConnectorStub.callCount, 1);233 assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/a.id?changelist=aTransport");234 assert.equal(oNewConnectorStub.getCall(0).args[1], "DELETE");235 });236 });237 QUnit.test("When prepareCreate is called and getting id of app variant is checked", function(assert) {238 return AppVariantFactory.prepareCreate({239 id: "a.id",240 reference: "a.reference"241 }).then(function(oVariant) {242 assert.strictEqual(oVariant.getId(), "a.id");243 });244 });245 QUnit.test("When prepareCreate is called and setting id of app variant is cross checked", function(assert) {246 return AppVariantFactory.prepareCreate({247 id: "a.id",248 reference: "a.reference"249 }).then(function(oVariant) {250 assert.strictEqual(oVariant.getReference(), "a.reference");251 oVariant.setReference("new.reference");252 assert.strictEqual(oVariant.getReference(), "new.reference");253 });254 });255 QUnit.test("When prepareCreate is called and setting incorrect id of app variant failed", function(assert) {256 return AppVariantFactory.prepareCreate({257 id: "a.id",258 reference: "a.reference"259 }).then(function(oVariant) {260 assert.strictEqual(oVariant.getReference(), "a.reference");261 oVariant.setReference(); // Setting reference with undefined value262 }).catch(function(sError) {263 assert.ok(sError);264 });265 });266 QUnit.test("When prepareCreate is called and getting id of reference app is checked", function(assert) {267 return AppVariantFactory.prepareCreate({268 id: "a.id",269 reference: "a.reference"270 }).then(function(oVariant) {271 assert.strictEqual(oVariant.getReference(), "a.reference");272 });273 });274 QUnit.test("When prepareCreate is called and getting version of an app variant is checked", function(assert) {275 return AppVariantFactory.prepareCreate({276 id: "a.id",277 reference: "a.reference",278 version: "1.0.0"279 }).then(function(oVariant) {280 assert.strictEqual(oVariant.getVersion(), "1.0.0");281 });282 });283 QUnit.test("When prepareCreate is called and namespace of an app variant is checked", function(assert) {284 return AppVariantFactory.prepareCreate({285 id: "a.id",286 reference: "a.reference"287 }).then(function(oVariant) {288 assert.strictEqual(oVariant.getNamespace(), "apps/a.reference/appVariants/a.id/");289 });290 });291 QUnit.test("When prepareCreate is called and setting transport is checked", function(assert) {292 var _oVariant;293 return AppVariantFactory.prepareCreate({294 id: "a.id",295 reference: "a.reference"296 }).then(function(oVariant) {297 _oVariant = oVariant;298 return oVariant.setTransportRequest("TR12345");299 }).then(function() {300 assert.equal(_oVariant.getTransportRequest(), "TR12345");301 });302 });303 QUnit.test("When prepareCreate is called and setting transport has wrong format", function(assert) {304 return AppVariantFactory.prepareCreate({305 id: "a.id",306 reference: "a.reference"307 }).then(function(oVariant) {308 return oVariant.setTransportRequest("WRONG_FORMAT");309 }).then(function() {310 assert.notOk("Should never succeed!");311 }).catch(function(sError) {312 assert.ok(sError);313 });314 });315 QUnit.test("When prepareCreate is called and setting package is checked", function(assert) {316 var _oVariant;317 return AppVariantFactory.prepareCreate({318 id: "a.id",319 reference: "a.reference"320 }).then(function(oVariant) {321 _oVariant = oVariant;322 return oVariant.setPackage("/ABC/DEFGH_IJKL12345");323 }).then(function() {324 assert.equal(_oVariant.getPackage(), "/ABC/DEFGH_IJKL12345");325 });326 });327 QUnit.test("When prepareCreate is called and setting package has wrong format", function(assert) {328 return AppVariantFactory.prepareCreate({329 id: "a.id",330 reference: "a.reference"331 }).then(function(oVariant) {332 return oVariant.setPackage("SomePackage_WrongFormat");333 }).then(function() {334 assert.notOk("Should never succeed!");335 }).catch(function(sError) {336 assert.ok(sError);337 });338 });339 QUnit.test("When prepareCreate is called and setting layer to customer", function(assert) {340 return AppVariantFactory.prepareCreate({341 id: "a.id",342 reference: "a.reference",343 layer: Layer.CUSTOMER344 }).then(function(oVariant) {345 assert.equal(oVariant._getMap().layer, "CUSTOMER");346 });347 });348 QUnit.test("When prepareCreate is called and setting layer to customer", function(assert) {349 return AppVariantFactory.prepareCreate({350 id: "a.id",351 reference: "a.reference",352 layer: Layer.CUSTOMER_BASE353 }).then(function(oVariant) {354 assert.equal(oVariant._getMap().layer, "CUSTOMER_BASE");355 });356 });357 QUnit.test("When prepareCreate is called and setting layer to partner", function(assert) {358 return AppVariantFactory.prepareCreate({359 id: "a.id",360 reference: "a.reference",361 layer: Layer.PARTNER362 }).then(function(oVariant) {363 assert.equal(oVariant._getMap().layer, "PARTNER");364 });365 });366 QUnit.test("When prepareCreate is called and setting layer to vendor", function(assert) {367 return AppVariantFactory.prepareCreate({368 id: "a.id",369 reference: "a.reference",370 layer: Layer.VENDOR371 }).then(function(oVariant) {372 assert.equal(oVariant._getMap().layer, "VENDOR");373 });374 });375 QUnit.test("When prepareCreate is called, variant saved into backend and checking app variant properties", function(assert) {376 return AppVariantFactory.prepareCreate({377 id: "a.id",378 reference: "a.reference"379 }).then(function(oVariant) {380 assert.notEqual(oVariant, null);381 assert.equal(oVariant.getId(), "a.id");382 assert.equal(oVariant.getReference(), "a.reference");383 assert.equal(oVariant.getMode(), "NEW");384 assert.equal(oVariant._getMap().layer, Layer.CUSTOMER);385 assert.equal(oVariant._getMap().fileType, "appdescr_variant");386 });387 });388 QUnit.test("When prepareCreate is called and failed with different possible failure options", function(assert) {389 return AppVariantFactory.prepareCreate({})390 .then(function() {391 assert.notOk("Should never succeed!");392 })393 .catch(function(sError) {394 assert.ok(sError);395 })396 .then(function() {397 return AppVariantFactory.prepareCreate({398 id: "a.id"399 });400 })401 .then(function() {402 assert.notOk("Should never succeed!");403 })404 .catch(function(sError) {405 assert.ok(sError);406 })407 .then(function() {408 return AppVariantFactory.prepareCreate({409 reference: "a.reference"410 });411 })412 .then(function() {413 assert.notOk("Should never succeed!");414 })415 .catch(function(sError) {416 assert.ok(sError);417 })418 .then(function() {419 return AppVariantFactory.createNew({420 id: 1,421 reference: "a.reference"422 });423 })424 .then(function() {425 assert.notOk("Should never succeed!");426 })427 .catch(function(sError) {428 assert.ok(sError);429 })430 .then(function() {431 return AppVariantFactory.createNew({432 id: "a.id",433 reference: 1434 });435 })436 .then(function() {437 assert.notOk("Should never succeed!");438 })439 .catch(function(sError) {440 assert.ok(sError);441 })442 .then(function() {443 return AppVariantFactory.createNew({444 id: "a.id",445 reference: "a.reference",446 version: 2447 });448 })449 .then(function() {450 assert.notOk("Should never succeed!");451 })452 .catch(function(sError) {453 assert.ok(sError);454 })455 .then(function() {456 return AppVariantFactory.createNew({457 id: "a.id",458 reference: "a.reference",459 layer: true460 });461 })462 .then(function() {463 assert.notOk("Should never succeed!");464 })465 .catch(function(sError) {466 assert.ok(sError);467 });468 });469 QUnit.test("When prepareCreate is called and app variant is submitted", function(assert) {470 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({471 response: JSON.stringify({472 id: "a.id",473 reference: "a.reference",474 layer: Layer.CUSTOMER475 })476 });477 return AppVariantFactory.prepareCreate({478 id: "a.id",479 reference: "a.reference"480 }).then(function(oAppVariant) {481 return oAppVariant.submit();482 }).then(function(oResponse) {483 assert.notEqual(oResponse, null);484 assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/?sap-language=en");485 });486 });487 QUnit.test("When prepareCreate is called with referenceVersion and app variant is submitted", function(assert) {488 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({489 response: JSON.stringify({490 id: "a.id",491 reference: "a.reference",492 layer: Layer.CUSTOMER493 })494 });495 return AppVariantFactory.prepareCreate({496 id: "a.id",497 reference: "a.reference",498 referenceVersion: "1.1"499 }).then(function(oAppVariant) {500 return oAppVariant.submit();501 }).then(function(oResponse) {502 assert.notEqual(oResponse, null);503 assert.equal(oNewConnectorStub.getCall(0).args[0], "/sap/bc/lrep/appdescr_variants/?sap-language=en");504 assert.equal(JSON.parse(oNewConnectorStub.getCall(0).args[2].payload).referenceVersion, "1.1");505 });506 });507 QUnit.test("When prepareUpdate is called with referenceVersion and app variant is submitted as a local object", function(assert) {508 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({509 response: JSON.stringify({510 id: "a.id",511 reference: "a.reference",512 layer: Layer.CUSTOMER513 })514 });515 var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: ""});516 return AppVariantFactory.prepareUpdate({517 id: "a.id"518 }).then(function(oAppVariant) {519 return oAppVariant.submit();520 }).then(function(oResponse) {521 assert.ok(oStubOpenTransportSelection.calledOnce);522 assert.notEqual(oResponse, null);523 assert.equal(oNewConnectorStub.callCount, 2);524 assert.equal(oNewConnectorStub.getCall(1).args[0], "/sap/bc/lrep/appdescr_variants/a.id?sap-language=en");525 });526 });527 QUnit.test("When prepareUpdate is called and app variant is submitted which is already published", function(assert) {528 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({529 response: JSON.stringify({530 id: "a.id",531 reference: "a.reference",532 layer: Layer.CUSTOMER533 })534 });535 var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: "aTransport"});536 return AppVariantFactory.prepareUpdate({537 id: "a.id"538 }).then(function(oAppVariant) {539 return oAppVariant.submit();540 }).then(function(oResponse) {541 assert.ok(oStubOpenTransportSelection.calledOnce);542 assert.notEqual(oResponse, null);543 assert.equal(oNewConnectorStub.callCount, 2);544 assert.equal(oNewConnectorStub.getCall(1).args[0], "/sap/bc/lrep/appdescr_variants/a.id?changelist=aTransport&sap-language=en");545 });546 });547 QUnit.test("When prepareDelete is called and app variant is deleted which was saved as a local object", function(assert) {548 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({549 response: JSON.stringify({550 id: "a.id",551 reference: "a.reference",552 layer: Layer.CUSTOMER553 })554 });555 var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: ""});556 return AppVariantFactory.prepareDelete({557 id: "a.id"558 }).then(function(oAppVariant) {559 return oAppVariant.submit();560 }).then(function(oResponse) {561 assert.ok(oStubOpenTransportSelection.calledOnce);562 assert.notEqual(oResponse, null);563 assert.equal(oNewConnectorStub.getCall(0).args[0], '/sap/bc/lrep/appdescr_variants/a.id');564 });565 });566 QUnit.test("When prepareDelete is called and app variant is deleted which was already published", function(assert) {567 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({568 response: JSON.stringify({569 id: "a.id",570 reference: "a.reference",571 layer: Layer.CUSTOMER572 })573 });574 var oStubOpenTransportSelection = sandbox.stub(TransportSelection.prototype, "openTransportSelection").resolves({transport: "aTransport"});575 return AppVariantFactory.prepareDelete({576 id: "a.id"577 }).then(function(oDescriptorVariant) {578 return oDescriptorVariant.submit();579 }).then(function(oResponse) {580 assert.ok(oStubOpenTransportSelection.calledOnce);581 assert.notEqual(oResponse, null);582 assert.equal(oNewConnectorStub.callCount, 2);583 assert.equal(oNewConnectorStub.getCall(1).args[0], '/sap/bc/lrep/appdescr_variants/a.id?changelist=aTransport');584 });585 });586 });587 QUnit.module("Given a AppVariantFactory for S4/Hana Cloud systems", {588 beforeEach: function() {589 //define sandboxes and stubs explicitly for each modules590 sandbox.stub(Settings, "getInstance").resolves(591 new Settings({592 isKeyUser: false,593 isAtoAvailable: true,594 isAtoEnabled: true,595 isProductiveSystem: false596 })597 );598 },599 afterEach: function() {600 sandbox.restore();601 }602 }, function() {603 QUnit.test("When prepareCreate is called and variant is saved into the backend", function(assert) {604 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({605 response: JSON.stringify({606 id: "a.id",607 reference: "a.reference",608 layer: "CUSTOMER",609 packageName: "YY1_DEFAULT_123"610 })611 });612 return AppVariantFactory.prepareCreate({613 id: "a.id",614 reference: "a.reference"615 }).then(function(oVariant) {616 return oVariant.submit();617 }).then(function(oResponse) {618 assert.notEqual(oResponse, null);619 assert.equal(oNewConnectorStub.getCall(0).args[0], '/sap/bc/lrep/appdescr_variants/?sap-language=en');620 });621 });622 QUnit.test("SmartBusiness: When prepareCreate is called and variant is saved into the backend", function(assert) {623 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({624 response: JSON.stringify({625 id: "a.id",626 reference: "a.reference",627 layer: "CUSTOMER",628 packageName: "YY1_DEFAULT_123"629 })630 });631 return AppVariantFactory.prepareCreate({632 id: "a.id",633 reference: "a.reference",634 transport: "ATO_NOTIFICATION"635 }).then(function(oVariant) {636 return oVariant.submit();637 }).then(function(oResponse) {638 assert.notEqual(oResponse, null);639 assert.equal(oNewConnectorStub.getCall(0).args[0], '/sap/bc/lrep/appdescr_variants/?changelist=ATO_NOTIFICATION&sap-language=en');640 });641 });642 QUnit.test("Smart Business: When prepareUpdate is called and variant was already published", function(assert) {643 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({644 response: JSON.stringify({645 id: "a.id",646 reference: "a.reference",647 layer: "CUSTOMER",648 packageName: "YY1_DEFAULT_123"649 })650 });651 return AppVariantFactory.prepareUpdate({652 id: "a.id"653 }).then(function(oVariant) {654 return oVariant.submit();655 }).then(function(oResponse) {656 assert.notEqual(oResponse, null);657 assert.equal(oNewConnectorStub.getCall(1).args[0], '/sap/bc/lrep/appdescr_variants/a.id?changelist=ATO_NOTIFICATION&sap-language=en');658 });659 });660 QUnit.test("Smart Business: When prepareUpdate is called and variant was already published", function(assert) {661 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({662 response: JSON.stringify({663 id: "a.id",664 reference: "a.reference",665 layer: "CUSTOMER",666 packageName: "YY1_DEFAULT_123"667 })668 });669 return AppVariantFactory.prepareUpdate({670 id: "a.id"671 }).then(function(oVariant) {672 return oVariant.submit();673 }).then(function(oResponse) {674 assert.notEqual(oResponse, null);675 assert.equal(oNewConnectorStub.getCall(1).args[0], '/sap/bc/lrep/appdescr_variants/a.id?changelist=ATO_NOTIFICATION&sap-language=en');676 });677 });678 QUnit.test("When prepareDelete is called to prepare a delete app variant config and submit is called to delete an app variant saved as local object", function(assert) {679 var oNewConnectorStub = sandbox.stub(WriteUtils, "sendRequest").resolves({680 response: JSON.stringify({681 id: "a.id",682 reference: "a.reference",683 layer: "CUSTOMER"...
roulette.js
Source:roulette.js
1const sql = require("better-sqlite3")("/Users/chase/Desktop/Coding/No Testu/source/userInfo.db");2const discord = require("discord.js");3module.exports.run = async(client, message, args) => {4// roulette functions5//wheel6var wheel ={7 0: "green", 8 1: "black", 9 2: "red"10};11//pick colour12function pickColour() {13 return(wheel [Object.keys(wheel)[Math.floor(Math.random() * Object.keys(wheel).length)]])14};15var colour = pickColour();16 //declare nums17 var greenNums = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]18 var blackNums = [16, 5, 3, 18, 7, 14, 12, 9, 11, 25, 34, 21, 32, 23, 30, 29, 36, 27]19 var redNums = [33, 20, 22, 26, 35, 28, 37, 31, 24, 6, 17, 2, 15, 10, 19, 8, 13, 4]20 //pick black num21 if (colour === "black") {22 function pickBlackNum () {23 return blackNums[Math.floor(Math.random() * blackNums.length)]24 };25 var num = pickBlackNum();26 }27 //pick red num28 else if (colour === "red") {29 function pickRedNum () {30 return redNums[Math.floor(Math.random() * redNums.length)]31 };32 var num = pickRedNum();33 }34 //pick green num35 else if (colour === "green") {36 function pickGreenNum () {37 return greenNums[Math.floor(Math.random() * greenNums.length)]38 };39 var num = pickGreenNum();40 }41 //check if number is even42 function isEven() {43 if (num % 2 == 0)44 return ("even");45 else 46 return ("odd");47 }48 var compare = isEven();49 //check what group number is in50 function numGroup(){51 if (num <= 18)52 return ("low");53 else54 return ("high");55 }56 var group = numGroup();57//user input58let msgArray = args // sets up array59let guessType = msgArray[0]; //colour number even/odd- black, red, gree60let guess = msgArray[1]; //black/red even/odd low/high- a single number61let wager = msgArray [2]; //5, 10, Moneys62//valid guessType check63let isValidType = ["color", "colour", "even/odd", "numbers", "number", "black", "red", "green"]64let validType = isValidType.includes(guessType)65 //if no guess type66 if(!guessType) {67 message.delete({ timeout: 4000 })68 message.channel.send("No Guess Type Provided. Please type colour, even/odd, numbers or the colour you want to bet on (green, black, or red) after the roulette command.")69 .then(msg => msg.delete({timeout: 4000}))70 .catch(err => console.log(err));71 return;72 }73 //if no guess74 else if(!guess) {75 message.delete({ timeout: 4000 })76 message.channel.send("No Betting Option Provided. Please type red, black, even, odd, low (for numbers 1-18), high (for numbers 19-37), or the specific number you want to bet on after the guess type.")77 .then(msg => msg.delete({timeout: 4000}))78 .catch(err => console.log(err));79 return;80 }81 //if no wager82 else if(!wager) {83 message.delete({ timeout: 4000 })84 message.channel.send("No wager provided. Please type the amount of Moneys you would like to bet (after the Roulette Wheel Number/Betting Option).")85 .then(msg => msg.delete({timeout: 4000}))86 .catch(err => console.log(err));87 return;88 }89 //if invalid guess type90 else if(validType === false) {91 message.delete({ timeout: 4000 })92 message.channel.send("Invalid Guess Type. Please type colour, even/odd, numbers, or the colour you want to bet on (green, black, or red) after the roulette command.")93 .then(msg => msg.delete({timeout: 4000}))94 .catch(err => console.log(err));95 return;96 }97 //check if valid guess- if guessType is valid and guess exists98 else if(validType === true && guess) {99 var valid; //true/false variable to be assigned to100 //valid variables based on guess type101 let isValidColour = ["black", "red"]102 let isValidEvenOdd = ["even", "odd"]103 let isValidGroup = ["low", "high"]104 let isValidRed = ["33", "20", "22", "26", "35", "28", "37", "31", "24", "6", "17", "2", "15", "10", "19", "8", "13", "4"]105 let isValidBlack = ["16","5", "3", "18", "7", "14", "12", "9", "11", "25", "34", "21", "32", "23", "30", "29", "36", "27"]106 let isValidGreen = ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]107 let groups = ["colour", "color", "number", "numbers", "even/odd"]108 let single = ["green", "red", "black"]109 //check if message content is in array based on guess type110 if(guessType === "colour" || guessType === "color"){valid = isValidColour.includes(guess)} //compares guess to isValidColour returns true or false111 else if(guessType === "even/odd"){valid = isValidEvenOdd.includes(guess)} //checks if user input is correct112 else if(guessType === "numbers" || guessType === "number"){valid = isValidGroup.includes(guess)} //and compares it to the array of "the wheel" (more like the groups on the wheel)113 else if(guessType === "black"){valid = isValidBlack.includes(guess)}114 else if(guessType === "red"){valid = isValidRed.includes(guess)}115 else if(guessType === "green"){valid = isValidGreen.includes(guess)}116 //if invalid guess for groups117 if (valid === false && groups.includes(guessType)) {118 message.delete({ timeout: 4000 })119 message.channel.send("Invalid Betting Option. Please type red, black, even, odd, low (for numbers 1-18), or high (for numbers 19-37) after the guess type.")120 .then(msg => msg.delete({timeout: 4000}))121 .catch(err => console.log(err));122 return;123 }124 //if guess type is single125 else if (valid === false && single.includes(guessType)) {126 let numGuess = parseInt(msgArray[1]); //number guess127 //if numGuess is NaN128 if(isNaN(numGuess)){129 message.delete({ timeout: 2000 })130 message.channel.send("Your guess must be a number!")131 .then(msg => msg.delete({timeout: 2000}))132 .catch(err => console.log(err));133 return;134 }135 //if invalid num136 else {137 message.delete({timeout: 4000})138 message.channel.send("Number/Colour combination does not exist. (If you need help- Look at a Roulette Wheel and add 1 to the number you want to bet on.)")139 .then(msg => msg.delete({timeout: 4000}))140 .catch(err => console.log(err));141 return;142 }143 }144 //if all is well145 else {146 //get user moneys147 let userID = message.author.id148 let prepareStatement = sql.prepare("SELECT * FROM data WHERE userID = ?")//select all(*) from the table called data (based on the column called userID)149 let userXpObject= prepareStatement.get(`${userID}`) //creates object with * (all) the user info in, on the row with the matching userID150 let newMoneys = parseInt(wager);// parseInt turns strings into integers- we are turning the user input into a usable number151 let currentMoneys = userXpObject["userMoneys"];152 //if wager is NAN153 if(isNaN(newMoneys)){154 message.delete({ timeout: 2000 })155 message.channel.send("Your wager must be a number!")156 .then(msg => msg.delete({timeout: 2000}))157 .catch(err => console.log(err));158 return;159 }160 //if wager > moneys161 if (wager > currentMoneys){162 message.delete({ timeout: 2000 })163 message.channel.send("Your wager is higher than the Moneys you have!")164 .then(msg => msg.delete({timeout: 2000}))165 .catch(err => console.log(err));166 return;167 }168 //SINGLE GUESS169 if (single.includes(guessType)) {170 let numGuess = parseInt(msgArray[1]); //number guess171 //if colour is right172 if (guessType === colour) {173 //win case174 if (numGuess === num) {175 let finalMoneys = newMoneys + currentMoneys176 let prepareUpdate = sql.prepare(`UPDATE data SET userMoneys = ? WHERE userID = ?`)177 prepareUpdate.run(finalMoneys, userID);178 const winEmbed = new discord.MessageEmbed()179 .setTitle("The ball landed on " + colour + " " + num )180 .setDescription("You Win " + wager + " Moneys!")181 .setColor("#0f5718")182 message.channel.send(winEmbed)183 }184 //lose case185 else if(numGuess !== num) {186 let finalMoneys = currentMoneys - newMoneys;187 let prepareUpdate = sql.prepare(`UPDATE data SET userMoneys = ? WHERE userID = ?`)188 prepareUpdate.run(finalMoneys, userID);189 const loseEmbed = new discord.MessageEmbed()190 .setTitle("The ball landed on " + colour + " " + num )191 .setDescription("You Lost " + wager + " Moneys!")192 .setColor("#ec2727")193 message.channel.send(loseEmbed)194 }195 }196 //if colour is wrong- lose case197 else if (guessType !== colour) {198 let finalMoneys = currentMoneys - newMoneys;199 let prepareUpdate = sql.prepare(`UPDATE data SET userMoneys = ? WHERE userID = ?`)200 prepareUpdate.run(finalMoneys, userID);201 const loseEmbed = new discord.MessageEmbed()202 .setTitle("The ball landed on " + colour + " " + num )203 .setDescription("You Lost " + wager + " Moneys!")204 .setColor("#ec2727")205 message.channel.send(loseEmbed)206 }207 }208 //GROUP GUESSES209 else {210 //if colour guess211 if (guessType === "colour" || guessType === "color"){212 //win case213 if (guess === colour){214 let finalMoneys = newMoneys + currentMoneys215 let prepareUpdate = sql.prepare(`UPDATE data SET userMoneys = ? WHERE userID = ?`)216 prepareUpdate.run(finalMoneys, userID);217 const winEmbed = new discord.MessageEmbed()218 .setTitle("The ball landed on " + colour + " " + num )219 .setDescription("You Win " + wager + " Moneys!")220 .setColor("#0f5718")221 message.channel.send(winEmbed)222 }223 //lose case224 else {225 let finalMoneys = currentMoneys - newMoneys;226 let prepareUpdate = sql.prepare(`UPDATE data SET userMoneys = ? WHERE userID = ?`)227 prepareUpdate.run(finalMoneys, userID);228 const loseEmbed = new discord.MessageEmbed()229 .setTitle("The ball landed on " + colour + " " + num )230 .setDescription("You Lost " + wager + " Moneys!")231 .setColor("#ec2727")232 message.channel.send(loseEmbed)233 }234 }235 //if even odd guess236 if(guessType === "even/odd"){237 //win case238 if (guess === compare){239 let finalMoneys = newMoneys + currentMoneys240 let prepareUpdate = sql.prepare(`UPDATE data SET userMoneys = ? WHERE userID = ?`)241 prepareUpdate.run(finalMoneys, userID);242 const winEmbed = new discord.MessageEmbed()243 .setTitle("The ball landed on " + colour + " " + num )244 .setDescription("You Win " + wager + " Moneys!")245 .setColor("#0f5718")246 message.channel.send(winEmbed)247 }248 //lose case249 else {250 let finalMoneys = currentMoneys - newMoneys;251 let prepareUpdate = sql.prepare(`UPDATE data SET userMoneys = ? WHERE userID = ?`)252 prepareUpdate.run(finalMoneys, userID);253 const loseEmbed = new discord.MessageEmbed()254 .setTitle("The ball landed on " + colour + " " + num )255 .setDescription("You Lost " + wager + " Moneys!")256 .setColor("#ec2727")257 message.channel.send(loseEmbed)258 }259 }260 //if number guess261 if(guessType === "number" || guessType === "numbers"){262 //win case263 if (guess === group) {264 let finalMoneys = newMoneys + currentMoneys265 let prepareUpdate = sql.prepare(`UPDATE data SET userMoneys = ? WHERE userID = ?`)266 prepareUpdate.run(finalMoneys, userID);267 const winEmbed = new discord.MessageEmbed()268 .setTitle("The ball landed on " + colour + " " + num )269 .setDescription("You Win " + wager + " Moneys!")270 .setColor("#0f5718")271 message.channel.send(winEmbed)272 }273 //lose case274 else {275 let finalMoneys = currentMoneys - newMoneys;276 let prepareUpdate = sql.prepare(`UPDATE data SET userMoneys = ? WHERE userID = ?`)277 prepareUpdate.run(finalMoneys, userID);278 const loseEmbed = new discord.MessageEmbed()279 .setTitle("The ball landed on " + colour + " " + num )280 .setDescription("You Lost " + wager + " Moneys!")281 .setColor("#ec2727")282 message.channel.send(loseEmbed)283 }284 }285 }286 }287 } 288}289module.exports.help = {290 name: "roulette",291 category: "fun",292 usage: `Template for Groups: PREFIXroulette guess-type betting-option wager\n Example (black): PREFIXroulette colour black 5 \nExample (red): PREFIXroulette colour red 5 \n Example (even): PREFIXroulette even/odd even 5 \nExample (odd): PREFIXroulette even/odd odd 5 \nExample (numbers 1-18):PREFIXroulette numbers low 5 \nExample (numbers 19-37):PREFIXroulette numbers high 5 \nTemplate for Single Number: PREFIXroulette colour number wager \n Example (red): PREFIXroulette red 17 5 \n Example (black): PREFIXroulette black 16 5 \n Example (green): PREFIXroulette green 1 5`,293 description: "This command allows you to bet either on a single number/colour combination, or on a group of the roulette wheel. Type the roulette command followed by a guess-type (colour, even/odd, numbers, black, red, or green), a betting-option (red, black; even, odd; low, high; one number you want to bet on), and how many Moneys you'd like to bet (Separated with spaces). I will spin the wheel and tell you if you've won."...
update.js
Source:update.js
...27 Mapper.update(null, null), [],28 'resolves multiple `null` value arguments to an empty array'29 );30 });31 t.test('Mapper.prepareUpdate()', st => {32 const Records = Mapper33 .table('records')34 .idAttribute('record_id')35 .prepareUpdate({ record_id: 5, text: 'a' });36 st.queriesEqual(37 Records.toQueryBuilder(), `38 update "records"39 set "text" = 'a'40 where "record_id" = 541 `, 'single record'42 );43 const PgRecords = Pg44 .table('records')45 .idAttribute('record_id')46 .prepareUpdate({ record_id: 5, text: 'a' });47 st.queriesEqual(48 PgRecords.toQueryBuilder(), `49 update "records"50 set "text" = 'a'51 where "record_id" = '5'52 returning *53 `, 'single record with PostgreSQL returning *'54 );55 st.throws(56 () => Mapper.prepareUpdate({}),57 UnidentifiableRecordError,58 'rejects with `UnidentifiableRecordError`'59 );60 st.throws(61 () => Mapper.prepareUpdate({ id: null }),62 UnidentifiableRecordError,63 'rejects with `UnidentifiableRecordError` on `null` key'64 );65 st.end();66 });67 t.test('Mapper.prepareUpdate() - composite keys', st => {68 const A = 'A';69 const B = 'B';70 const Composite = Pg.table('things').idAttribute([A, B]);71 st.throws(72 () => Composite.prepareUpdate({}),73 UnidentifiableRecordError,74 'rejects with `UnidentifiableRecordError` on empty record'75 );76 st.throws(77 () => Composite.prepareUpdate({A}),78 UnidentifiableRecordError,79 'rejects with `UnidentifiableRecordError` on one key missing'80 );81 st.throws(82 () => Composite.prepareUpdate({A: null, B}),83 UnidentifiableRecordError,84 'rejects with `UnidentifiableRecordError` when one key is null'85 );86 const UpdateComposite = Composite.prepareUpdate(87 {A: 'valA', B: 'valB', name: 'Bob' }88 );89 st.queriesEqual(90 UpdateComposite.toQueryBuilder(), `91 update "things"92 set "name" = 'Bob'93 where "A" = 'valA' and "B" = 'valB'94 returning *95 `, 'single record with PostgreSQL returning *'96 );97 st.end();98 });99 t.test('Mapper.handleUpdateRowResponse() - data response', st => {100 const record = { id: 5, name: 'Bob' };101 const result = Mapper.handleUpdateRowResponse({102 response: [{ id: 5, updated_at: 'time' }], record103 });104 st.deepEqual(105 result,106 { id: 5, updated_at: 'time', name: 'Bob' },107 'result is correct when response is row data array'108 );109 st.deepEqual(110 record,111 { id: 5, name: 'Bob' },112 'original record is unchanged'113 );114 st.end();115 });116 t.test('Mapper.handleUpdateRowResponse() - changed count response', st => {117 const record = { id: 5, name: 'Bob' };118 const result = Mapper.handleUpdateRowResponse({119 response: 1, record120 });121 st.deepEqual(122 result,123 { id: 5, name: 'Bob' },124 'result is correct when response is count'125 );126 st.equal(result, record,127 'record returned when response is count'128 );129 st.end();130 });131 t.test('Mapper.require().handleUpdateRowResponse()', st => {132 st.throws(133 () => Mapper.require().handleUpdateRowResponse({ response: 0 }),134 NotFoundError,135 'Throws `NotFoundError` when response is `0`'136 );137 st.throws(138 () => Mapper.require().handleUpdateRowResponse({ response: [] }),139 NotFoundError,140 'Throws `NotFoundError` when response is `[]`'141 );142 st.end();143 });144 t.test('Mapper.defaultAttributes().prepareUpdate()', st => {145 const Defaults = Mapper.table('table').defaultAttributes({146 default: 'default'147 });148 st.queriesEqual(149 Defaults.prepareUpdate({ id: 1, value: 'value' }).toQueryBuilder(),150 `update "table" set "value" = 'value' where "id" = 1`,151 'does not affect update query'152 );153 st.end();154 });155 t.test('Mapper.strictAttributes().prepareUpdate()', st => {156 const Strict = Mapper.table('table').strictAttributes({157 strict: 'strict',158 other: attributes => attributes.id159 });160 st.queriesEqual(161 Strict.prepareUpdate({ id: 1, strict: 'overridden' }).toQueryBuilder(),162 `update "table" set "other" = 1, "strict" = 'strict' where "id" = 1`163 );164 const FnStrict = Mapper.table('table').setState({165 testState: 'testValue'166 }).strictAttributes({167 strict() { return this.requireState('testState'); }168 });169 st.queriesEqual(170 FnStrict171 .prepareUpdate({ id: 2, strict: 'overridden' })172 .toQueryBuilder(),173 `update "table" set "strict" = 'testValue' where "id" = 2`174 );175 st.end();176 });177 t.end();...
deleteForward.js
Source:deleteForward.js
...36 const firstSplitOffset = splitTextNode(this, offset);37 const secondSplitOffset = splitTextNode(parentNode.childNodes[firstSplitOffset], charSize);38 const middleNode = parentNode.childNodes[firstSplitOffset];39 // Do remove the character, then restore the state of the surrounding parts.40 const restore = prepareUpdate(parentNode, firstSplitOffset, parentNode, secondSplitOffset);41 const isSpace = !isVisibleStr(middleNode) && !isInPre(middleNode);42 const isZWS = middleNode.nodeValue === '\u200B';43 middleNode.remove();44 restore();45 // If the removed element was not visible content, propagate the delete.46 if (47 isZWS ||48 (isSpace &&49 getState(parentNode, firstSplitOffset, DIRECTIONS.RIGHT).cType !== CTYPES.CONTENT)50 ) {51 parentNode.oDeleteForward(firstSplitOffset, alreadyMoved);52 if (isZWS) {53 fillEmpty(parentNode);54 }55 return;56 }57 fillEmpty(parentNode);58 setSelection(parentNode, firstSplitOffset);59};60HTMLElement.prototype.oDeleteForward = function (offset) {61 const filterFunc = node =>62 isVisibleEmpty(node) || isContentTextNode(node) || isNotEditableNode(node);63 const firstLeafNode = findNode(rightLeafOnlyNotBlockNotEditablePath(this, offset), filterFunc);64 if (firstLeafNode &&65 isZWS(firstLeafNode) &&66 this.parentElement.hasAttribute('oe-zws-empty-inline')67 ) {68 const grandparent = this.parentElement.parentElement;69 if (!grandparent) {70 return;71 }72 const parentIndex = childNodeIndex(this.parentElement);73 const restore = prepareUpdate(...boundariesOut(this.parentElement));74 this.parentElement.remove();75 restore();76 HTMLElement.prototype.oDeleteForward.call(grandparent, parentIndex);77 return;78 }79 if (80 this.hasAttribute &&81 this.hasAttribute('oe-zws-empty-inline') &&82 (83 isZWS(this) ||84 (this.textContent === '' && this.childNodes.length === 0)85 )86 ) {87 const parent = this.parentElement;88 if (!parent) {89 return;90 }91 const index = childNodeIndex(this);92 const restore = prepareUpdate(...boundariesOut(this));93 this.remove();94 restore();95 HTMLElement.prototype.oDeleteForward.call(parent, index);96 return;97 }98 if (firstLeafNode && (isFontAwesome(firstLeafNode) || isNotEditableNode(firstLeafNode))) {99 firstLeafNode.remove();100 return;101 }102 if (103 firstLeafNode &&104 (firstLeafNode.nodeName !== 'BR' ||105 getState(...rightPos(firstLeafNode), DIRECTIONS.RIGHT).cType !== CTYPES.BLOCK_INSIDE)106 ) {...
frame.js
Source:frame.js
1function Frame() {2}3Frame.prototype.delete=function(pkName,url,successcCallback){4 successcCallback=successcCallback||tableUtil.remove;5 var selects =tableUtil.getSelections();6 if(selects.length==0){7 dialog.alert("请éæ©è¦å é¤çæ°æ®");8 return;9 }10 var count=selects.length;11 dialog.confirm('ç¡®å®è¦å é¤è¿'+count+"æ¡æ°æ®å?",function(){12 var data='';13 var ids=[];14 for(var i=0;i<selects.length;i++){15 data+=pkName+"="+selects[i][pkName]+"&";16 ids.push(selects[i][pkName]);17 }18 ajaxUtil.json(url,data,function(resp){19 if(!resp.success){20 dialog.alert(resp.message);21 }else{22 successcCallback(pkName,ids);23 }24 })25 });26}27//æ¾ç¤ºä¿®æ¹é¡µé¢28Frame.prototype.openUpdate=function (pkName,title,prepareUrl,updateUrl,size,successCallback) {29 size=size||2;30 successCallback=successCallback||tableUtil.update;31 ajaxUtil.html(prepareUrl,null,function(content){32 content="<form id='prepareUpdate'>"+content+"</form>";33 var vue=null;34 dialog.createPop('prepareUpdate',title,content,size,function (data) {35 var validate= vue.$validator.validateAll();36 validate.then((result)=>{37 if(result){38 $('#pop'+'prepareUpdate').modal('hide');39 var data=$("#prepareUpdate").serialize();40 ajaxUtil.json(updateUrl,data,function(rest){41 if(rest.success){42 successCallback(rest.data[pkName],rest.data);43 }else{44 dialog.alert(rest.message);45 }46 });47 }48 })49 return false;50 });51 vue=vueUtil.init({52 el:"#prepareUpdate",53 data:updateData54 });55 });56}57Frame.prototype.update=function (pkName, title,prepareUrl,updateUrl,size) {58 var selects = tableUtil.getSelections();59 if(selects.length==0){60 dialog.alert("请éæ©è¦ä¿®æ¹çæ°æ®");61 return;62 }63 if(selects.length!=1){64 dialog.alert("æ¯æ¬¡åªè½ä¿®æ¹1æ¡");65 return;66 }67 prepareUrl=prepareUrl+'?'+pkName+'='+selects[0][pkName];68 frame.openUpdate(pkName,title,prepareUrl,updateUrl,size);69}70Frame.prototype.prepareInsert=function (title, prepareUrl, insertUrl,successCallback,size,param) {71 size=size||2;72 successCallback=successCallback||tableUtil.insertRow;73 ajaxUtil.html(prepareUrl,param,function(content){74 content="<form id='prepareInsert'>"+content+"</form>";75 var vue=null;76 dialog.createPop('prepareInsert',title,content,size,function (data) {77 var validate= vue.$validator.validateAll();78 validate.then((result)=>{79 if(result){80 $('#pop'+'prepareInsert').modal('hide');81 var data=$("#prepareInsert").serialize();82 ajaxUtil.json(insertUrl,data,function(rest){83 if(rest.success){84 successCallback(rest.data);85 }else{86 dialog.alert(rest.message);87 }88 });89 }90 })91 return false;92 });93 vue=vueUtil.init({94 el:"#prepareInsert",95 data:insertData96 });97 });98}99Frame.prototype.search=function (formId,url,vue) {100 var validate= vue.$validator.validateAll();101 validate.then((result)=>{102 if(result){103 tableUtil.loadByForm(formId,url);104 }105 })106}...
perf.js
Source:perf.js
...64 console.timeEnd("perf: update [band][row,column]");65});66test("perf: prepareUpdate [band][row,column]", ({ eq }) => {67 console.time("perf: prepareUpdate [band][row,column]");68 const update = prepareUpdate({ data: im_data, layout: im_layout, sizes: im_sizes });69 for (let b = 0; b < im_sizes.band; b++) {70 for (let r = 0; r < im_sizes.row; r++) {71 for (let c = 0; c < im_sizes.column; c++) {72 update({ point: { band: b, row: r, column: c }, value: 10 });73 }74 }75 }76 console.timeEnd("perf: prepareUpdate [band][row,column]");77});78test("perf: transform [band][row,column] to [row,column,band]", ({ eq }) => {79 console.time("perf: transform [band][row,column] to [row,column,band]");80 transform({81 data,82 from: im_layout,...
notification.js
Source:notification.js
1import React, {Component} from 'react';2import { Platform } from 'react-native';3// import firebase from 'react-native-firebase';4/**5 * Class for handling notifications.6 */7class Notification extends Component {8 /**9 * Creates an instance of Notification.10 * @constructor11 */12 constructor(props){13 super(props);14 //firebase.initializeApp(config);15 this.notification = null;16 }17 /**18 * Check if user has permission to receive notification19 * if has permission, then ask for a device token20 * if not, rejected the request and user will not receive notification21 */22 async checkPermission() {23 if (Platform.OS === 'ios') {24 return false;25 }26 const enabled = await firebase.messaging().hasPermission();27 //enabled: ask firebase if user has permission to request firebase messaging28 if (enabled){29 return this.getToken();30 }31 else{32 return false;33 }34 }35 /**36 * Request a device token37 */38 async getToken(){39 if (Platform.OS === 'ios') {40 return false;41 }42 const fcmToken = await firebase.messaging().getToken();43 if (fcmToken) {44 //console.log(`token is:${fcmToken}`)45 const fcm = fcmToken;46 const newData = {data:{}};47 newData.data.id = AuthState.getCurrentUserID();48 newData.data.deviceToken = fcm ;49 console.log(fcm);50 const prepareUpdate = newData.data;51 Database.editProfileData(prepareUpdate, ()=>{this._callback(true)}, ()=>{this._callback(false)});52// Database.editProfileData(prepareUpdate, (data) => {53// this._callback(true);54// },(error) => {55// this._callback(false);56// });57 } else {58 // user doesn't have a device token yet59 console.log('user doesnt have a device token yet');60 return false;61 }62 }63 /**64 * Create a new channel for Android user to receive notification65 */66 createChannel(){67 if (Platform.OS === 'ios') {68 return null;69 }70 const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max)71 .setDescription('My apps test channel');72 return (channel);73 }74 /**75 * Delete device token76 */77 async removeToken(){78 if (Platform.OS === 'ios') {79 return null;80 }81 await firebase.messaging().deleteToken();82 const prepareUpdate = {};83 prepareUpdate.id = AuthState.getCurrentUserID();84 prepareUpdate.deviceToken = "";85 Database.editProfileData(prepareUpdate, ()=>{this._callback(true)}, ()=>{this._callback(false)});86 }87 deleteNotificationArea(){88 const prepareUpdate = {};89 prepareUpdate.id = AuthState.getCurrentUserID();90 prepareUpdate.hasCircle = false;91 Database.editProfileData(prepareUpdate, ()=>{this._callback(true)}, ()=>{this._callback(false)});92}93}94const NotificationMethod = new Notification();...
warn.js
Source:warn.js
1const sql = require("better-sqlite3")("/Users/chase/Desktop/Coding/No Testu/source/userInfo.db");2const discord = require("discord.js");3module.exports.run = async(client, message, args) => {4 if(!message.member.hasPermission("ADMINISTRATOR")) {5 message.channel.send("You cannot warn people.").then(msg => msg.delete({timeout: 2000})).catch(err => console.log(err)); 6 message.delete(); return;7 }8 let msgArray = message.content.substring(6).split (", ")9 let userID = msgArray[0]10 let reason = msgArray[1]11 if (!userID){12 message.channel.send("You must provide a userID").then(msg => msg.delete({timeout: 2000})).catch(err => console.log(err)); 13 message.delete(); return;14 }15 if (!reason){16 message.channel.send("You must provide a reason").then(msg => msg.delete({timeout: 2000})).catch(err => console.log(err)); 17 message.delete(); return;18 }19 let prepareStatement = sql.prepare("SELECT * FROM data WHERE userID = ?")20 let userObject= prepareStatement.get(`${userID}`)21 let warnReas = userObject["warnReason"]22 let newReas = reason23 let finalReason = warnReas + ", " + newReas24 let warnAmt = userObject["warnNum"]25 let newNum = 126 let finalWarn = warnAmt + newNum27 let username = userObject["username"]28 if (warnReas === "N/A"){29 let prepareUpdate = sql.prepare(`UPDATE data SET warnNum = ?, warnReason = ? WHERE userID = ?`)30 prepareUpdate.run(finalWarn, newReas, userID);31 } else{32 let prepareUpdate = sql.prepare(`UPDATE data SET warnNum = ?, warnReason = ? WHERE userID = ?`)33 prepareUpdate.run(finalWarn, finalReason, userID);34 }35 const warnEmbed = new discord.MessageEmbed()36 .setTitle(`${username} has been Warned!`)37 .setDescription(`Reason: ${reason}`)38 .setColor("#831313")39 message.channel.send(warnEmbed)40}41module.exports.help = {42 name: "warn",43 category: "admin",44 usage: `Template: PREFIXwarn userID, reason\n Example: PREFIXwarn 735157583010332723, a good reason (the user ID is my alt acct)`,45 description: "For warning members. Type the command followed by the userID and the reason for the warning (MUST BE Separated with a comma)."...
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 [request] = await Promise.all([7 page.waitForRequest(request => request.url().includes('q=playwright') && request.method() === 'GET'),8 page.click('text="Playwright"'),9 ]);10 console.log(request.url());11 await browser.close();12})();13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 const [request] = await Promise.all([19 page.waitForRequest(request => request.url().includes('q=playwright') && request.method() === 'GET'),20 page.click('text="Playwright"'),21 ]);22 console.log(request.url());23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 const [request] = await Promise.all([31 page.waitForRequest(request => request.url().includes('q=playwright') && request.method() === 'GET'),32 page.click('text="Playwright"'),33 ]);34 console.log(request.url());35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 const [request] = await Promise.all([43 page.waitForRequest(request => request.url().includes('q=playwright') && request.method() === 'GET'),44 page.click('text="Playwright"'),45 ]);46 console.log(request.url());47 await browser.close();48})();
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 await page.evaluate(() => {7 const a = document.createElement('a');8 a.target = '_blank';9 a.textContent = 'Open New Window';10 document.body.appendChild(a);11 });12 const [popup] = await Promise.all([13 ]);14 await popup.waitForLoadState('domcontentloaded');15 await popup.close();16 await browser.close();17})();
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 await page.waitForSelector('text=Get started');7 await page.click('text=Get started');8 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');9 await page.click('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');10 await page.waitForSelector('text=Get started');11 await page.click('text=Get started');12 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');13 await page.click('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');14 await page.waitForSelector('text=Get started');15 await page.click('text=Get started');16 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');17 await page.click('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');18 await page.waitForSelector('text=Get started');19 await page.click('text=Get started');20 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');21 await page.click('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');22 await page.waitForSelector('text=Get started');23 await page.click('text=Get started');24 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');25 await page.click('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');26 await page.waitForSelector('text=Get started');27 await page.click('text=Get started');28 await page.waitForSelector('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API');29 await page.click('text=Playwright is a Node library to automate Chromium, Firefox and WebKit with a
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.click('text=Get started');6 await page.waitForTimeout(3000);7 await page.close();8 await browser.close();9})();
Using AI Code Generation
1const {chromium} = require('playwright');2const { prepareUpdate } = require('playwright/lib/server/browserType');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const context = await browser.newContext();7 const page2 = await context.newPage();8 await page2.close();9 await context.close();10 await browser.close();11})();12const {chromium} = require('playwright');13const { prepareUpdate } = require('playwright/lib/server/browserType');14(async () => {15 const browser = await chromium.launch();16 const page = await browser.newPage();17 const context = await browser.newContext();18 const page2 = await context.newPage();19 await page2.close();20 await context.close();21 await browser.close();22})();23const {chromium} = require('playwright');24const { prepareUpdate } = require('playwright/lib/server/browserType');25(async () => {26 const browser = await chromium.launch();27 const page = await browser.newPage();28 const context = await browser.newContext();29 const page2 = await context.newPage();30 await page2.close();31 await context.close();32 await browser.close();33})();34const {chromium} = require('playwright');35const { prepareUpdate } = require('playwright/lib/server/browserType');36(async () => {37 const browser = await chromium.launch();38 const page = await browser.newPage();39 const context = await browser.newContext();40 const page2 = await context.newPage();41 await page2.close();42 await context.close();43 await browser.close();44})();45const {chromium} = require('playwright');46const { prepareUpdate } = require('playwright
Using AI Code Generation
1const { chromium } = require('playwright');2const { prepareUpdate } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');3(async() => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await prepareUpdate(page);7})();8const { chromium } = require('playwright');9const { prepareUpdate } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');10(async() => {11 const browser = await chromium.launch();12 const page = await browser.newPage();13 await prepareUpdate(page);14})();15const { chromium } = require('playwright');16const { prepareUpdate } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');17(async() => {18 const browser = await chromium.launch();19 const page = await browser.newPage();20 await prepareUpdate(page);21})();22const { chromium } = require('playwright');23const { prepareUpdate } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');24(async() => {25 const browser = await chromium.launch();26 const page = await browser.newPage();27 await prepareUpdate(page);28})();29const { chromium } = require('playwright');30const { prepareUpdate } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');31(async() => {32 const browser = await chromium.launch();33 const page = await browser.newPage();34 await prepareUpdate(page);35})();36const { chromium } = require('playwright');37const { prepareUpdate } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');38(async() => {
Using AI Code Generation
1const { chromium } = require('playwright');2const { prepareUpdate } = require('playwright/lib/server/registry');3const path = require('path');4(async () => {5 const browser = await chromium.launch({ headless: false });6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.click('text=Docs');9 await prepareUpdate(path.join(__dirname, 'browser'), 'chromium');10 await browser.close();11})();12at Object.waitWithTimeout (node_modules\playwright\lib\utils\helper.js:243:15)13at BrowserServer._waitForCloseOrTimeout (node_modules\playwright\lib\server\browserServer.js:86:28)14at async BrowserServer.waitForClose (node_modules\playwright\lib\server\browserServer.js:69:16)15at async Object.launch (node_modules\playwright\lib\server\chromium.js:130:21)16at async Object.<anonymous> (test.js:7:23)
Using AI Code Generation
1const { prepareUpdate } = require('playwright/lib/server/update');2(async () => {3 await prepareUpdate();4})();5const { prepareUpdate } = require('playwright/lib/server/update');6(async () => {7 await prepareUpdate();8})();9const { prepareUpdate } = require('playwright/lib/server/update');10(async () => {11 await prepareUpdate();12})();13const { prepareUpdate } = require('playwright/lib/server/update');14(async () => {15 await prepareUpdate();16})();17const { prepareUpdate } = require('playwright/lib/server/update');18(async () => {19 await prepareUpdate();20})();21const { prepareUpdate } = require('playwright/lib/server/update');22(async () => {23 await prepareUpdate();24})();25const { prepareUpdate } = require('playwright/lib/server/update');26(async () => {27 await prepareUpdate();28})();29const { prepareUpdate } = require('playwright/lib/server/update');30(async () => {31 await prepareUpdate();32})();33const { prepareUpdate } = require('playwright/lib/server/update');34(async () => {35 await prepareUpdate();36})();37const { prepareUpdate } = require('playwright/lib/server/update');38(async () => {39 await prepareUpdate();40})();41const { prepareUpdate } = require('playwright/lib/server/update');42(async () => {43 await prepareUpdate();44})();45const { prepareUpdate } = require('playwright/lib/server/update');46(async () => {47 await prepareUpdate();48})();
Using AI Code Generation
1const { prepareUpdate } = require('playwright-core/lib/server/supplements/recorder/patch');2const { chromium } = require('playwright-core');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const update = prepareUpdate(page, 'click', 'text="Google Search"');7 await page.click('text="Google Search"');8 update();9})();10const { prepareUpdate } = require('playwright-core/lib/server/supplements/recorder/patch');11const { chromium } = require('playwright-core');12(async () => {13 const browser = await chromium.launch();14 const page = await browser.newPage();15 const update = prepareUpdate(page, 'click', 'text="Google Search"');16 await page.click('text="Google Search"');17 update();18})();19const { prepareUpdate } = require('playwright-core/lib/server/supplements/recorder/patch');20const { chromium } = require('playwright-core');21(async () => {22 const browser = await chromium.launch();23 const page = await browser.newPage();24 const update = prepareUpdate(page, 'click', 'text="Google Search"');25 await page.click('text="Google Search"');26 update();27})();28const { prepareUpdate } = require('playwright-core/lib/server/supplements/recorder/patch');29const { chromium } = require('playwright-core');30(async () => {31 const browser = await chromium.launch();32 const page = await browser.newPage();33 const update = prepareUpdate(page, 'click', 'text="Google Search"');
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!!