Best JavaScript code snippet using wpt
mock-rippled.ts
Source:mock-rippled.ts
...16}17function isBTC(json) {18 return json === 'BTC' || json === '0000000000000000000000004254430000000000'19}20function createResponse(request, response, overrides = {}) {21 const result = _.assign({}, response.result, overrides)22 const change =23 response.result && !_.isEmpty(overrides)24 ? {id: request.id, result: result}25 : {id: request.id}26 return JSON.stringify(_.assign({}, response, change))27}28function createLedgerResponse(request, response) {29 const newResponse = JSON.parse(createResponse(request, response))30 if (newResponse.result && newResponse.result.ledger) {31 if (!request.transactions) {32 delete newResponse.result.ledger.transactions33 }34 if (!request.accounts) {35 delete newResponse.result.ledger.accountState36 }37 // the following fields were not in the ledger response in the past38 if (newResponse.result.ledger.close_flags === undefined) {39 newResponse.result.ledger.close_flags = 040 }41 if (newResponse.result.ledger.parent_close_time === undefined) {42 newResponse.result.ledger.parent_close_time =43 newResponse.result.ledger.close_time - 1044 }45 }46 return JSON.stringify(newResponse)47}48// We mock out WebSocketServer in these tests and add a lot of custom49// properties not defined on the normal WebSocketServer object.50type MockedWebSocketServer = any51export function createMockRippled(port) {52 const mock = new WebSocketServer({port: port}) as MockedWebSocketServer53 _.assign(mock, EventEmitter2.prototype)54 const close = mock.close55 mock.close = function() {56 if (mock.expectedRequests !== undefined) {57 const allRequestsMade = _.every(mock.expectedRequests, function(counter) {58 return counter === 059 })60 if (!allRequestsMade) {61 const json = JSON.stringify(mock.expectedRequests, null, 2)62 const indent = ' '63 const indented = indent + json.replace(/\n/g, '\n' + indent)64 assert(false, 'Not all expected requests were made:\n' + indented)65 }66 }67 close.call(mock)68 }69 mock.expect = function(expectedRequests) {70 mock.expectedRequests = expectedRequests71 }72 mock.on('connection', function(this: MockedWebSocketServer, conn: any) {73 if (mock.config.breakNextConnection) {74 mock.config.breakNextConnection = false75 conn.terminate()76 return77 }78 this.socket = conn79 conn.config = {}80 conn.on('message', function(requestJSON) {81 try {82 const request = JSON.parse(requestJSON)83 mock.emit('request_' + request.command, request, conn)84 } catch (err) {85 console.error('Error: ' + err.message)86 assert(false, err.message)87 }88 })89 })90 mock.config = {}91 mock.onAny(function(this: MockedWebSocketServer) {92 if (this.event.indexOf('request_') !== 0) {93 return94 }95 if (mock.listeners(this.event).length === 0) {96 throw new Error('No event handler registered for ' + this.event)97 }98 if (mock.expectedRequests === undefined) {99 return // TODO: fail here to require expectedRequests100 }101 const expectedCount = mock.expectedRequests[this.event]102 if (expectedCount === undefined || expectedCount === 0) {103 throw new Error('Unexpected request: ' + this.event)104 }105 mock.expectedRequests[this.event] -= 1106 })107 mock.on('request_config', function(request, conn) {108 assert.strictEqual(request.command, 'config')109 conn.config = _.assign(conn.config, request.data)110 conn.send(111 createResponse(request, {112 status: 'success',113 type: 'response',114 result: {}115 })116 )117 })118 mock.on('request_test_command', function(request, conn) {119 assert.strictEqual(request.command, 'test_command')120 if (request.data.disconnectIn) {121 setTimeout(conn.terminate.bind(conn), request.data.disconnectIn)122 conn.send(123 createResponse(request, {124 status: 'success',125 type: 'response',126 result: {}127 })128 )129 } else if (request.data.openOnOtherPort) {130 getFreePort().then(newPort => {131 createMockRippled(newPort)132 conn.send(133 createResponse(request, {134 status: 'success',135 type: 'response',136 result: {port: newPort}137 })138 )139 })140 } else if (request.data.closeServerAndReopen) {141 setTimeout(() => {142 conn.terminate()143 close.call(mock, () => {144 setTimeout(() => {145 createMockRippled(port)146 }, request.data.closeServerAndReopen)147 })148 }, 10)149 } else if (request.data.unrecognizedResponse) {150 conn.send(151 createResponse(request, {152 status: 'unrecognized',153 type: 'response',154 result: {}155 })156 )157 }158 })159 mock.on('request_global_config', function(request, conn) {160 assert.strictEqual(request.command, 'global_config')161 mock.config = _.assign(conn.config, request.data)162 conn.send(163 createResponse(request, {164 status: 'success',165 type: 'response',166 result: {}167 })168 )169 })170 mock.on('request_echo', function(request, conn) {171 assert.strictEqual(request.command, 'echo')172 conn.send(JSON.stringify(request.data))173 })174 mock.on('request_server_info', function(request, conn) {175 assert.strictEqual(request.command, 'server_info')176 if (conn.config.highLoadFactor || conn.config.loadFactor) {177 const response = {178 id: 0,179 status: 'success',180 type: 'response',181 result: {182 info: {183 build_version: '0.24.0-rc1',184 complete_ledgers: '32570-6595042',185 hostid: 'ARTS',186 io_latency_ms: 1,187 last_close: {188 converge_time_s: 2.007,189 proposers: 4190 },191 load_factor: conn.config.loadFactor || 4294967296,192 peers: 53,193 pubkey_node: 'n94wWvFUmaKGYrKUGgpv1DyYgDeXRGdACkNQaSe7zJiy5Znio7UC',194 server_state: 'full',195 validated_ledger: {196 age: 5,197 base_fee_xrp: 0.00001,198 hash:199 '4482DEE5362332F54A4036ED57EE1767C9F33CF7CE5A6670355C16CECE381D46',200 reserve_base_xrp: 20,201 reserve_inc_xrp: 5,202 seq: 6595042203 },204 validation_quorum: 3205 }206 }207 }208 conn.send(createResponse(request, response))209 } else if (conn.config.returnErrorOnServerInfo) {210 conn.send(createResponse(request, fixtures.server_info.error))211 } else if (conn.config.disconnectOnServerInfo) {212 conn.close()213 } else if (conn.config.serverInfoWithoutValidated) {214 conn.send(createResponse(request, fixtures.server_info.noValidated))215 } else if (mock.config.returnSyncingServerInfo) {216 mock.config.returnSyncingServerInfo--217 conn.send(createResponse(request, fixtures.server_info.syncing))218 } else {219 conn.send(createResponse(request, fixtures.server_info.normal))220 }221 })222 mock.on('request_subscribe', function(request, conn) {223 assert.strictEqual(request.command, 'subscribe')224 if (request && request.streams === 'validations') {225 conn.send(createResponse(request, fixtures.subscribe_error))226 } else if (mock.config.returnEmptySubscribeRequest) {227 mock.config.returnEmptySubscribeRequest--228 conn.send(createResponse(request, fixtures.empty))229 } else if (request.accounts) {230 assert(_.indexOf(_.values(addresses), request.accounts[0]) !== -1)231 }232 conn.send(createResponse(request, fixtures.subscribe))233 })234 mock.on('request_unsubscribe', function(request, conn) {235 assert.strictEqual(request.command, 'unsubscribe')236 if (request.accounts) {237 assert(_.indexOf(_.values(addresses), request.accounts[0]) !== -1)238 } else {239 assert.deepEqual(request.streams, ['ledger', 'server'])240 }241 conn.send(createResponse(request, fixtures.unsubscribe))242 })243 mock.on('request_account_objects', function(request, conn) {244 assert.strictEqual(request.command, 'account_objects')245 if (request.account === addresses.ACCOUNT) {246 conn.send(accountObjectsResponse(request))247 } else {248 assert(false, 'Unrecognized account address: ' + request.account)249 }250 })251 mock.on('request_account_info', function(request, conn) {252 assert.strictEqual(request.command, 'account_info')253 if (request.account === addresses.ACCOUNT) {254 conn.send(createResponse(request, fixtures.account_info.normal))255 } else if (request.account === addresses.NOTFOUND) {256 conn.send(createResponse(request, fixtures.account_info.notfound))257 } else if (request.account === addresses.THIRD_ACCOUNT) {258 const response = Object.assign({}, fixtures.account_info.normal)259 response.Account = addresses.THIRD_ACCOUNT260 conn.send(createResponse(request, response))261 } else if (request.account === undefined) {262 const response = Object.assign(263 {},264 {265 error: 'invalidParams',266 error_code: 31,267 error_message: "Missing field 'account'.",268 id: 2,269 request: {command: 'account_info', id: 2},270 status: 'error',271 type: 'response'272 }273 )274 conn.send(createResponse(request, response))275 } else {276 const response = Object.assign(277 {},278 {279 account: request.account,280 error: 'actNotFound',281 error_code: 19,282 error_message: 'Account not found.',283 id: 2,284 ledger_current_index: 17714714,285 request:286 // This will be inaccurate, but that's OK because this is just a mock rippled287 {288 account: 'rogvkYnY8SWjxkJNgU4ZRVfLeRyt5DR9i',289 command: 'account_info',290 id: 2291 },292 status: 'error',293 type: 'response',294 validated: false295 }296 )297 conn.send(createResponse(request, response))298 }299 })300 mock.on('request_ledger', function(request, conn) {301 assert.strictEqual(request.command, 'ledger')302 if (request.ledger_index === 34) {303 conn.send(createLedgerResponse(request, fixtures.ledger.notFound))304 } else if (request.ledger_index === 6) {305 conn.send(createResponse(request, fixtures.ledger.withStateAsHashes))306 } else if (request.ledger_index === 9038215) {307 conn.send(createLedgerResponse(request, fixtures.ledger.withoutCloseTime))308 } else if (request.ledger_index === 4181996) {309 conn.send(createLedgerResponse(request, fixtures.ledger.withSettingsTx))310 } else if (311 request.ledger_index === 22420574 &&312 request.expand === true &&313 request.transactions === true314 ) {315 conn.send(316 createLedgerResponse(request, fixtures.ledger.withPartialPayment)317 )318 } else if (request.ledger_index === 100001) {319 conn.send(320 createLedgerResponse(request, fixtures.ledger.pre2014withPartial)321 )322 } else if (request.ledger_index === 38129) {323 const response = _.assign({}, fixtures.ledger.normal, {324 result: {ledger: fullLedger}325 })326 conn.send(createLedgerResponse(request, response))327 } else if (328 request.ledger_hash ===329 '15F20E5FA6EA9770BBFFDBD62787400960B04BE32803B20C41F117F41C13830D'330 ) {331 conn.send(createLedgerResponse(request, fixtures.ledger.normalByHash))332 } else if (333 request.ledger_index === 'validated' ||334 request.ledger_index === 14661789 ||335 request.ledger_index === 14661788 /* getTransaction - order */336 ) {337 conn.send(createLedgerResponse(request, fixtures.ledger.normal))338 } else {339 assert(false, 'Unrecognized ledger request: ' + JSON.stringify(request))340 }341 })342 mock.on('request_ledger_data', function(request, conn) {343 assert.strictEqual(request.command, 'ledger_data')344 if (request.marker) {345 conn.send(createResponse(request, fixtures.ledger_data.last_page))346 } else {347 conn.send(createResponse(request, fixtures.ledger_data.first_page))348 }349 })350 mock.on('request_ledger_entry', function(request, conn) {351 assert.strictEqual(request.command, 'ledger_entry')352 if (353 request.index ===354 'E30E709CF009A1F26E0E5C48F7AA1BFB79393764F15FB108BDC6E06D3CBD8415'355 ) {356 conn.send(createResponse(request, fixtures.payment_channel.normal))357 } else if (358 request.index ===359 'D77CD4713AA08195E6B6D0E5BC023DA11B052EBFF0B5B22EDA8AE85345BCF661'360 ) {361 conn.send(createResponse(request, fixtures.payment_channel.full))362 } else if (363 request.index ===364 '8EF9CCB9D85458C8D020B3452848BBB42EAFDDDB69A93DD9D1223741A4CA562B'365 ) {366 conn.send(createResponse(request, fixtures.escrow))367 } else {368 conn.send(createResponse(request, fixtures.ledger_entry.error))369 }370 })371 mock.on('request_ping', function(request, conn) {372 // NOTE: We give the response a timeout of 2 second, so that tests can373 // set their timeout threshold to greater than or less than this number374 // to test timeouts.375 setTimeout(() => {376 conn.send(377 createResponse(request, {378 result: {},379 status: 'success',380 type: 'response'381 })382 )383 }, 1000 * 2)384 })385 mock.on('request_tx', function(request, conn) {386 assert.strictEqual(request.command, 'tx')387 if (request.transaction === hashes.VALID_TRANSACTION_HASH) {388 conn.send(createResponse(request, fixtures.tx.Payment))389 } else if (390 request.transaction ===391 '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B'392 ) {393 conn.send(createResponse(request, fixtures.tx.AccountSet))394 } else if (395 request.transaction ===396 '8925FC8844A1E930E2CC76AD0A15E7665AFCC5425376D548BB1413F484C31B8C'397 ) {398 conn.send(createResponse(request, fixtures.tx.AccountSetTrackingOn))399 } else if (400 request.transaction ===401 'C8C5E20DFB1BF533D0D81A2ED23F0A3CBD1EF2EE8A902A1D760500473CC9C582'402 ) {403 conn.send(createResponse(request, fixtures.tx.AccountSetTrackingOff))404 } else if (405 request.transaction ===406 '278E6687C1C60C6873996210A6523564B63F2844FB1019576C157353B1813E60'407 ) {408 conn.send(createResponse(request, fixtures.tx.RegularKey))409 } else if (410 request.transaction ===411 '10A6FB4A66EE80BED46AAE4815D7DC43B97E944984CCD5B93BCF3F8538CABC51'412 ) {413 conn.send(createResponse(request, fixtures.tx.OfferCreate))414 } else if (415 request.transaction ===416 '458101D51051230B1D56E9ACAFAA34451BF65FA000F95DF6F0FF5B3A62D83FC2'417 ) {418 conn.send(createResponse(request, fixtures.tx.OfferCreateSell))419 } else if (420 request.transaction ===421 '809335DD3B0B333865096217AA2F55A4DF168E0198080B3A090D12D88880FF0E'422 ) {423 conn.send(createResponse(request, fixtures.tx.OfferCancel))424 } else if (425 request.transaction ===426 '635A0769BD94710A1F6A76CDE65A3BC661B20B798807D1BBBDADCEA26420538D'427 ) {428 conn.send(createResponse(request, fixtures.tx.TrustSet))429 } else if (430 request.transaction ===431 '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA11'432 ) {433 conn.send(createResponse(request, fixtures.tx.NoLedgerIndex))434 } else if (435 request.transaction ===436 '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA12'437 ) {438 conn.send(createResponse(request, fixtures.tx.NoLedgerFound))439 } else if (440 request.transaction ===441 '0F7ED9F40742D8A513AE86029462B7A6768325583DF8EE21B7EC663019DD6A04'442 ) {443 conn.send(createResponse(request, fixtures.tx.LedgerWithoutTime))444 } else if (445 request.transaction ===446 'FE72FAD0FA7CA904FB6C633A1666EDF0B9C73B2F5A4555D37EEF2739A78A531B'447 ) {448 conn.send(createResponse(request, fixtures.tx.TrustSetFrozenOff))449 } else if (450 request.transaction ===451 'BAF1C678323C37CCB7735550C379287667D8288C30F83148AD3C1CB019FC9002'452 ) {453 conn.send(createResponse(request, fixtures.tx.TrustSetNoQuality))454 } else if (455 request.transaction ===456 '9D6AC5FD6545B2584885B85E36759EB6440CDD41B6C55859F84AFDEE2B428220'457 ) {458 conn.send(createResponse(request, fixtures.tx.TrustSetAddMemo))459 } else if (460 request.transaction ===461 '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA10'462 ) {463 conn.send(createResponse(request, fixtures.tx.NotValidated))464 } else if (request.transaction === hashes.NOTFOUND_TRANSACTION_HASH) {465 conn.send(createResponse(request, fixtures.tx.NotFound))466 } else if (467 request.transaction ===468 '097B9491CC76B64831F1FEA82EAA93BCD728106D90B65A072C933888E946C40B'469 ) {470 conn.send(createResponse(request, fixtures.tx.OfferWithExpiration))471 }472 // Checks473 else if (474 request.transaction ===475 '605A2E2C8E48AECAF5C56085D1AEAA0348DC838CE122C9188F94EB19DA05C2FE'476 ) {477 conn.send(createResponse(request, fixtures.tx.CheckCreate))478 } else if (479 request.transaction ===480 'B4105D1B2D83819647E4692B7C5843D674283F669524BD50C9614182E3A12CD4'481 ) {482 conn.send(createResponse(request, fixtures.tx.CheckCancel))483 } else if (484 request.transaction ===485 '8321208465F70BA52C28BCC4F646BAF3B012BA13B57576C0336F42D77E3E0749'486 ) {487 conn.send(createResponse(request, fixtures.tx.CheckCash))488 }489 // Escrows490 else if (491 request.transaction ===492 '144F272380BDB4F1BD92329A2178BABB70C20F59042C495E10BF72EBFB408EE1'493 ) {494 conn.send(createResponse(request, fixtures.tx.EscrowCreation))495 } else if (496 request.transaction ===497 'F346E542FFB7A8398C30A87B952668DAB48B7D421094F8B71776DA19775A3B22'498 ) {499 conn.send(createResponse(request, fixtures.tx.EscrowCancellation))500 } else if (501 request.transaction ===502 'CC5277137B3F25EE8B86259C83CB0EAADE818505E4E9BCBF19B1AC6FD136993B'503 ) {504 conn.send(createResponse(request, fixtures.tx.EscrowExecution))505 } else if (506 request.transaction ===507 'CC5277137B3F25EE8B86259C83CB0EAADE818505E4E9BCBF19B1AC6FD1369931'508 ) {509 conn.send(createResponse(request, fixtures.tx.EscrowExecutionSimple))510 }511 // Payment Channels512 else if (513 request.transaction ===514 '0E9CA3AB1053FC0C1CBAA75F636FE1EC92F118C7056BBEF5D63E4C116458A16D'515 ) {516 conn.send(createResponse(request, fixtures.tx.PaymentChannelCreate))517 } else if (518 request.transaction ===519 'CD053D8867007A6A4ACB7A432605FE476D088DCB515AFFC886CF2B4EB6D2AE8B'520 ) {521 conn.send(createResponse(request, fixtures.tx.PaymentChannelFund))522 } else if (523 request.transaction ===524 '81B9ECAE7195EB6E8034AEDF44D8415A7A803E14513FDBB34FA984AB37D59563'525 ) {526 conn.send(createResponse(request, fixtures.tx.PaymentChannelClaim))527 } else if (528 request.transaction ===529 'EC2AB14028DC84DE525470AB4DAAA46358B50A8662C63804BFF38244731C0CB9'530 ) {531 conn.send(createResponse(request, fixtures.tx.AccountDelete))532 } else if (533 request.transaction ===534 'AFB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA11'535 ) {536 conn.send(createResponse(request, fixtures.tx.Unrecognized))537 } else if (538 request.transaction ===539 'AFB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B'540 ) {541 conn.send(createResponse(request, fixtures.tx.NoMeta))542 } else if (543 request.transaction ===544 '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA13'545 ) {546 conn.send(createResponse(request, fixtures.tx.LedgerZero))547 } else if (548 request.transaction ===549 'A971B83ABED51D83749B73F3C1AAA627CD965AFF74BE8CD98299512D6FB0658F'550 ) {551 conn.send(createResponse(request, fixtures.tx.Amendment))552 } else if (553 request.transaction ===554 'C6A40F56127436DCD830B1B35FF939FD05B5747D30D6542572B7A835239817AF'555 ) {556 conn.send(createResponse(request, fixtures.tx.SetFee))557 } else {558 assert(false, 'Unrecognized transaction hash: ' + request.transaction)559 }560 })561 mock.on('request_submit', function(request, conn) {562 assert.strictEqual(request.command, 'submit')563 if (request.tx_blob === 'BAD') {564 conn.send(createResponse(request, fixtures.submit.failure))565 } else {566 conn.send(createResponse(request, fixtures.submit.success))567 }568 })569 mock.on('request_submit_multisigned', function(request, conn) {570 assert.strictEqual(request.command, 'submit_multisigned')571 conn.send(createResponse(request, fixtures.submit.success))572 })573 mock.on('request_account_lines', function(request, conn) {574 if (request.account === addresses.ACCOUNT) {575 conn.send(accountLinesResponse.normal(request))576 } else if (request.account === addresses.OTHER_ACCOUNT) {577 conn.send(accountLinesResponse.counterparty(request))578 } else if (request.account === addresses.THIRD_ACCOUNT) {579 conn.send(accountLinesResponse.manyItems(request))580 } else if (request.account === addresses.NOTFOUND) {581 conn.send(createResponse(request, fixtures.account_info.notfound))582 } else {583 assert(false, 'Unrecognized account address: ' + request.account)584 }585 })586 mock.on('request_account_tx', function(request, conn) {587 if (request.account === addresses.ACCOUNT) {588 conn.send(transactionsResponse(request))589 } else if (request.account === addresses.OTHER_ACCOUNT) {590 conn.send(createResponse(request, fixtures.account_tx.one))591 } else {592 assert(false, 'Unrecognized account address: ' + request.account)593 }594 })595 mock.on('request_account_offers', function(request, conn) {596 if (request.account === addresses.ACCOUNT) {597 conn.send(fixtures.account_offers(request))598 } else {599 assert(false, 'Unrecognized account address: ' + request.account)600 }601 })602 let requestsCache = undefined603 mock.on('request_book_offers', function(request, conn) {604 if (request.taker_pays.issuer === 'rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw') {605 conn.send(createResponse(request, fixtures.book_offers.xrp_usd))606 } else if (607 request.taker_gets.issuer === 'rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw'608 ) {609 conn.send(createResponse(request, fixtures.book_offers.usd_xrp))610 } else if (611 isBTC(request.taker_gets.currency) &&612 isUSD(request.taker_pays.currency)613 ) {614 conn.send(615 fixtures.book_offers.fabric.requestBookOffersBidsResponse(request)616 )617 } else if (618 isUSD(request.taker_gets.currency) &&619 isBTC(request.taker_pays.currency)620 ) {621 conn.send(622 fixtures.book_offers.fabric.requestBookOffersAsksResponse(request)623 )624 } else {625 const rippledDir = 'test/fixtures/rippled'626 if (!requestsCache) {627 requestsCache = fs.readdirSync(rippledDir + '/requests')628 }629 for (var i = 0; i < requestsCache.length; i++) {630 const file = requestsCache[i]631 const json = fs.readFileSync(rippledDir + '/requests/' + file, 'utf8')632 const r = JSON.parse(json)633 const requestWithoutId = Object.assign({}, request)634 delete requestWithoutId.id635 if (JSON.stringify(requestWithoutId) === JSON.stringify(r)) {636 const responseFile =637 rippledDir + '/responses/' + file.split('.')[0] + '-res.json'638 const res = fs.readFileSync(responseFile, 'utf8')639 const response = createResponse(request, {640 id: 0,641 type: 'response',642 status: 'success',643 result: JSON.parse(res)644 })645 conn.send(response)646 return647 }648 }649 assert(false, 'Unrecognized order book: ' + JSON.stringify(request))650 }651 })652 mock.on('request_ripple_path_find', function(request, conn) {653 let response = null654 if (request.subcommand === 'close') {655 // for path_find command656 return657 }658 if (request.source_account === 'rB2NTuTTS3eNCsWxZYzJ4wqRqxNLZqA9Vx') {659 // getPaths - result path has source_amount in drops660 response = createResponse(request, {661 id: 0,662 type: 'response',663 status: 'success',664 result: {665 alternatives: [666 {667 destination_amount: {668 currency: 'EUR',669 issuer: 'rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u',670 value: '1'671 },672 paths_canonical: [],673 paths_computed: [674 [675 {676 currency: 'USD',677 issuer: 'rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u',678 type: 48,679 type_hex: '0000000000000030'680 },681 {682 currency: 'EUR',683 issuer: 'rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u',684 type: 48,685 type_hex: '0000000000000030'686 }687 ]688 ],689 source_amount: '1000000'690 }691 ],692 destination_account: 'rhpJkBfZGQyT1xeDbwtKEuSrSXw3QZSAy5',693 destination_amount: {694 currency: 'EUR',695 issuer: 'rGpGaj4sxEZGenW1prqER25EUi7x4fqK9u',696 value: '-1'697 },698 destination_currencies: ['EUR', 'XRP'],699 full_reply: true,700 id: 2,701 source_account: 'rB2NTuTTS3eNCsWxZYzJ4wqRqxNLZqA9Vx',702 status: 'success'703 }704 })705 } else if (request.source_account === addresses.NOTFOUND) {706 response = createResponse(request, fixtures.path_find.srcActNotFound)707 } else if (request.source_account === addresses.SOURCE_LOW_FUNDS) {708 response = createResponse(request, fixtures.path_find.sourceAmountLow)709 } else if (request.source_account === addresses.OTHER_ACCOUNT) {710 response = createResponse(request, fixtures.path_find.sendUSD)711 } else if (request.source_account === addresses.THIRD_ACCOUNT) {712 response = createResponse(request, fixtures.path_find.XrpToXrp, {713 destination_amount: request.destination_amount,714 destination_address: request.destination_address715 })716 } else if (request.source_account === addresses.ACCOUNT) {717 if (718 request.destination_account === 'ra5nK24KXen9AHvsdFTKHSANinZseWnPcX' &&719 // Important: Ensure that destination_amount.value is correct720 request.destination_amount.value === '-1'721 ) {722 response = createResponse(request, fixtures.path_find.sendAll)723 } else {724 response = fixtures.path_find.generate.generateIOUPaymentPaths(725 request.id,726 request.source_account,727 request.destination_account,728 request.destination_amount729 )730 }731 } else {732 assert(733 false,734 'Unrecognized path find request: ' + JSON.stringify(request)735 )736 }737 conn.send(response)738 })739 mock.on('request_gateway_balances', function(request, conn) {740 if (request.ledger_index === 123456) {741 conn.send(createResponse(request, fixtures.unsubscribe))742 } else {743 conn.send(createResponse(request, fixtures.gateway_balances))744 }745 })746 return mock...
handler.ts
Source:handler.ts
...77 try {78 await loginSchema.validateAsync(JSON.parse(event.body));79 const response = await UserService.login(event);80 logger.info("success!");81 return createResponse(response.code, response);82 } catch (error) {83 logger.error(error);84 return createResponse(HTTPStatusCodes.BAD_REQUEST, {85 code: 400,86 message: error.details[0].message,87 data: null,88 });89 } finally {90 logger.info("connection closed");91 }92};93export const xdrLogin = async (94 event: APIGatewayEvent,95 context: Context96) => {97 context.callbackWaitsForEmptyEventLoop = false;98 try {99 await loginWithSecretSchema.validateAsync(JSON.parse(event.body));100 const post = await UserService.xdrLogin(event);101 logger.info("success!");102 return createResponse(post.code, post);103 } catch (error) {104 logger.error(error);105 return createResponse(HTTPStatusCodes.BAD_REQUEST, {106 code: 400,107 message: error.details[0].message,108 data: null,109 });110 } finally {111 logger.info("connection closed");112 }113};114export const register = async (event: APIGatewayEvent, context: Context) => {115 context.callbackWaitsForEmptyEventLoop = false;116 try {117 await registerSchema.validateAsync(JSON.parse(event.body));118 let post = await UserService.register(event);119 logger.info("success!");120 return createResponse(post.code, post);121 } catch (error) {122 logger.error(error);123 return createResponse(HTTPStatusCodes.BAD_REQUEST, {124 code: 400,125 message: error.details[0].message,126 data: null,127 });128 } finally {129 logger.info("connection closed");130 }131};132export const getAccount = async (event: APIGatewayEvent, context: Context) => {133 context.callbackWaitsForEmptyEventLoop = false;134 try {135 const auth = await authMiddleware(event, ["1", "2", "3", "4", "5"]);136 if (auth.data == null) {137 return createResponse(auth.code, auth);138 }139 let post = await UserService.getAccount(event);140 logger.info("success!");141 return createResponse(post.code, post);142 } catch (error) {143 logger.error(error);144 return createResponse(HTTPStatusCodes.BAD_REQUEST, {145 code: 400,146 message: error.details[0].message,147 data: null,148 });149 } finally {150 logger.info("connection closed");151 }152};153export const searchAccounts = async (event: APIGatewayEvent, context: Context) => {154 context.callbackWaitsForEmptyEventLoop = false;155 try {156 const auth = await authMiddleware(event, ["1", "2", "3", "4", "5"]);157 if (auth.data == null) {158 return createResponse(auth.code, auth);159 }160 let post = await UserService.searchAccounts(event);161 logger.info("success!");162 return createResponse(post.code, post);163 } catch (error) {164 logger.error(error);165 return createResponse(HTTPStatusCodes.BAD_REQUEST, {166 code: 400,167 message: error.details[0].message,168 data: null,169 });170 } finally {171 logger.info("connection closed");172 }173};174export const editInitiative = async (175 event: APIGatewayEvent,176 context: Context177) => {178 context.callbackWaitsForEmptyEventLoop = false;179 try {180 const auth = await authMiddleware(event, ["1", "2", "3", "4", "5"]);181 if (auth.data == null) {182 return createResponse(auth.code, auth);183 }184 await editInitiativeSchema.validateAsync(JSON.parse(event.body));185 let post = await UserService.editInitiative(event);186 logger.info("success!");187 return createResponse(post.code, post);188 } catch (error) {189 logger.error(error);190 return createResponse(HTTPStatusCodes.BAD_REQUEST, {191 code: 400,192 message: error.details[0].message,193 data: null,194 });195 } finally {196 logger.info("connection closed");197 }198};199export const deleteInitiative = async (200 event: APIGatewayEvent,201 context: Context202) => {203 context.callbackWaitsForEmptyEventLoop = false;204 try {205 const auth = await authMiddleware(event, ["1", "2", "3", "4", "5"]);206 if (auth.data == null) {207 return createResponse(auth.code, auth);208 }209 let post = await UserService.deleteInitiative(event);210 logger.info("success!");211 return createResponse(post.code, post);212 } catch (error) {213 logger.error(error);214 return createResponse(HTTPStatusCodes.BAD_REQUEST, {215 code: 400,216 message: error.details[0].message,217 data: null,218 });219 } finally {220 logger.info("connection closed");221 }222};223export const getInitiative = async (224 event: APIGatewayEvent,225 context: Context226) => {227 context.callbackWaitsForEmptyEventLoop = false;228 try {229 230 let post = await UserService.getInitiative(event);231 logger.info("success!");232 return createResponse(post.code, post);233 } catch (error) {234 logger.error(error);235 return createResponse(HTTPStatusCodes.BAD_REQUEST, {236 code: 400,237 message: error.details[0].message,238 data: null,239 });240 } finally {241 logger.info("connection closed");242 }243};244export const listInitiatives = async (245 event: APIGatewayEvent,246 context: Context247) => {248 context.callbackWaitsForEmptyEventLoop = false;249 try {250 let post = await UserService.listInitiatives(event);251 logger.info("success!");252 return createResponse(post.code, post);253 } catch (error) {254 logger.error(error);255 return createResponse(HTTPStatusCodes.BAD_REQUEST, {256 code: 400,257 message: error.details[0].message,258 data: null,259 });260 } finally {261 logger.info("connection closed");262 }263};264export const searchInitiatives = async (265 event: APIGatewayEvent,266 context: Context267) => {268 context.callbackWaitsForEmptyEventLoop = false;269 try {270 let post = await UserService.searchInitiatives(event);271 logger.info("success!");272 return createResponse(post.code, post);273 } catch (error) {274 logger.error(error);275 return createResponse(HTTPStatusCodes.BAD_REQUEST, {276 code: 400,277 message: error.details[0].message,278 data: null,279 });280 } finally {281 logger.info("connection closed");282 }283};284export const addInitiative = async (285 event: APIGatewayEvent,286 context: Context287) => {288 context.callbackWaitsForEmptyEventLoop = false;289 try {290 const auth = await authMiddleware(event, ["1", "2", "3", "4", "5"]);291 if (auth.data == null) {292 return createResponse(auth.code, auth);293 }294 await addInitiativeSchema.validateAsync(JSON.parse(event.body));295 let post = await UserService.addInitiative(event);296 logger.info("success!");297 return createResponse(post.code, post);298 } catch (error) {299 logger.error(error);300 return createResponse(HTTPStatusCodes.BAD_REQUEST, {301 code: 400,302 message: error.details[0].message,303 data: null,304 });305 } finally {306 logger.info("connection closed");307 }308};309export const fundTransaction = async (310 event: APIGatewayEvent,311 context: Context312) => {313 context.callbackWaitsForEmptyEventLoop = false;314 try {315 const auth = await authMiddleware(event, ["1", "2", "3", "4", "5"]);316 if (auth.data == null) {317 return createResponse(auth.code, auth);318 }319 await fundTranasctionSchema.validateAsync(JSON.parse(event.body));320 let post = await UserService.fundTransaction(event);321 logger.info("success!");322 return createResponse(post.code, post);323 } catch (error) {324 logger.error(error);325 return createResponse(HTTPStatusCodes.BAD_REQUEST, {326 code: 400,327 message: error.details[0].message,328 data: null,329 });330 } finally {331 logger.info("connection closed");332 }333};334export const addKYC = async (335 event: APIGatewayEvent,336 context: Context337) => {338 context.callbackWaitsForEmptyEventLoop = false;339 try {340 const auth = await authMiddleware(event, ["1", "2", "3", "4", "5"]);341 if (auth.data == null) {342 return createResponse(auth.code, auth);343 }344 await addKYCSchema.validateAsync(JSON.parse(event.body));345 let post = await UserService.addKYC(event);346 logger.info("success!");347 return createResponse(post.code, post);348 } catch (error) {349 logger.error(error);350 return createResponse(HTTPStatusCodes.BAD_REQUEST, {351 code: 400,352 message: error.details[0].message,353 data: null,354 });355 } finally {356 logger.info("connection closed");357 }...
meetings.repository.spec.ts
Source:meetings.repository.spec.ts
1import { Meeting } from '../models/meeting.model';2import { Participant } from '../models/participant.model';3import GeFirestoreDatabase from '../utils/firebase';4import {MeetingsRepository} from "./meetings.repository";5describe('Meeting repository', () => {6 const validMeeting = new Meeting(7 "test meeting",8 new Date().toISOString(),9 new Date().toISOString(),10 [11 new Participant(12 "test@test.com",13 false,14 false,15 ),16 ],17 10,18 true,19 "passcode",20 "description",21 "public-meeting-id",22 "zoom-meeting-id",23 "fake-user-id");24 const mockWithConverter = jest.fn(() => {25 return {26 add: jest.fn().mockReturnValue({27 id: "fake-id3",28 }),29 set: jest.fn(),30 get: jest.fn().mockReturnValue({31 id: "fake-id",32 exists: true,33 empty: false,34 docs: [35 {36 id: "fake-id",37 exists: true,38 data() {return validMeeting},39 },40 ],41 join: jest.fn(),42 }),43 delete: jest.fn(),44 update: jest.fn(),45 } 46 }); 47 const mockCollection = jest.fn(() => {48 return {49 withConverter: mockWithConverter,50 doc: jest.fn(() => {51 return {52 update: jest.fn(),53 withConverter: mockWithConverter,54 join: jest.fn(),55 } 56 }),57 where: jest.fn(() => {58 return {59 where: jest.fn(() => {60 return {61 withConverter: mockWithConverter,62 }63 }),64 withConverter: mockWithConverter,65 }66 }),67 }68 }); 69 const mockGetInstance = jest.fn();70 mockGetInstance.mockReturnValue({71 getStore: {72 collection: mockCollection,73 },74 });75 function getMock(mock: any) {76 77 const mockCollection1 = jest.fn(() => {78 return {79 withConverter: mock,80 doc: jest.fn(() => {81 return {82 update: jest.fn(),83 withConverter: mock,84 } 85 }),86 where: jest.fn(() => {87 return {88 where: jest.fn(() => {89 return {90 withConverter: mockWithConverter,91 }92 }),93 withConverter: mockWithConverter,94 }95 }),96 }97 });98 99 const mockGetInstance1 = jest.fn();100 101 mockGetInstance1.mockReturnValue({102 getStore: {103 collection: mockCollection1,104 },105 });106 return mockGetInstance1;107 }108 109 beforeEach(() => {110 GeFirestoreDatabase.getInstance = mockGetInstance;111 });112 test('meeting repository - create successfully', async () => {113 expect(validMeeting).not.toBeNull();114 const meeetingRepository = new MeetingsRepository(GeFirestoreDatabase.getInstance().getStore);115 expect(meeetingRepository).not.toBeNull();116 const createResponse = await meeetingRepository.create(validMeeting);117 expect(createResponse).not.toBeNull();118 expect(createResponse.isSuccessful).toBeTruthy();119 });120 test('meeting repository - create response 500', async () => {121 expect(validMeeting).not.toBeNull();122 const mockWithConverter1 = jest.fn(() => {123 throw new Error("Fake error");124 });125 const meeetingRepository = new MeetingsRepository(getMock(mockWithConverter1)().getStore);126 expect(meeetingRepository).not.toBeNull();127 const createResponse = await meeetingRepository.create(validMeeting);128 expect(createResponse).not.toBeNull();129 expect(createResponse.isSuccessful).toBeFalsy();130 expect(createResponse.statusCode).toEqual(500);131 });132 test('meeting repository - update successfully', async () => {133 expect(validMeeting).not.toBeNull();134 const meeetingRepository = new MeetingsRepository(GeFirestoreDatabase.getInstance().getStore);135 expect(meeetingRepository).not.toBeNull();136 const createResponse = await meeetingRepository.update(validMeeting);137 expect(createResponse).not.toBeNull();138 expect(createResponse.isSuccessful).toBeTruthy();139 });140 test('meeting repository - update response 500', async () => {141 expect(validMeeting).not.toBeNull();142 const mockWithConverter1 = jest.fn(() => {143 throw new Error("Fake error");144 });145 const meeetingRepository = new MeetingsRepository(getMock(mockWithConverter1)().getStore);146 expect(meeetingRepository).not.toBeNull();147 const createResponse = await meeetingRepository.update(validMeeting);148 expect(createResponse).not.toBeNull();149 expect(createResponse.isSuccessful).toBeFalsy();150 expect(createResponse.statusCode).toEqual(500);151 });152 test('meeting repository - get successfully', async () => {153 const meetingId = "fake-id";154 expect(validMeeting).not.toBeNull();155 const meeetingRepository = new MeetingsRepository(GeFirestoreDatabase.getInstance().getStore);156 expect(meeetingRepository).not.toBeNull();157 const createResponse = await meeetingRepository.get(meetingId, "fake-user-id");158 expect(createResponse).not.toBeNull();159 expect(createResponse.isSuccessful).toBeTruthy();160 });161 test('meeting repository - get response 404', async () => {162 const meetingId = "fake-meeting-id";163 expect(validMeeting).not.toBeNull();164 const mockWithConverter1 = jest.fn(() => {165 return {166 add: jest.fn().mockReturnValue({167 id: "fake-id3",168 }),169 set: jest.fn(),170 get: jest.fn().mockReturnValue({171 id: "fake-id",172 exists: false,173 data() {return { id: "fake-id"}},174 empty: true,175 docs: [176 {177 id: "fake-id",178 exists: true,179 data() {return { id: "fake-id"}},180 },181 ],182 join: jest.fn(),183 }),184 delete: jest.fn(),185 } 186 });187 const meeetingRepository = new MeetingsRepository(getMock(mockWithConverter1)().getStore);188 expect(meeetingRepository).not.toBeNull();189 const createResponse = await meeetingRepository.get(meetingId, "fake-user-id");190 expect(createResponse).not.toBeNull();191 expect(createResponse.isSuccessful).toBeFalsy();192 expect(createResponse.statusCode).toEqual(404);193 });194 test('meeting repository - get response 500', async () => {195 const meetingId = "fake-meeting-id";196 expect(validMeeting).not.toBeNull();197 const mockCollection1 = jest.fn(() => {198 return {199 withConverter: jest.fn(() => {200 throw new Error()201 }),202 doc: jest.fn(() => {203 throw new Error()204 }),205 where: jest.fn(() => {206 throw new Error()207 }),208 }209 });210 const mock = jest.fn().mockReturnValue({211 getStore: {212 collection: mockCollection1,213 },214 });215 const meeetingRepository = new MeetingsRepository(mock().getStore);216 expect(meeetingRepository).not.toBeNull();217 const createResponse = await meeetingRepository.get(meetingId, "fake-user-id");218 expect(createResponse).not.toBeNull();219 expect(createResponse.isSuccessful).toBeFalsy();220 expect(createResponse.statusCode).toEqual(500);221 });222 test('meeting repository - delete successfully', async () => {223 const meetingId = "fake-id";224 expect(validMeeting).not.toBeNull();225 const meeetingRepository = new MeetingsRepository(GeFirestoreDatabase.getInstance().getStore);226 expect(meeetingRepository).not.toBeNull();227 const createResponse = await meeetingRepository.delete(meetingId, "fake-user-id");228 expect(createResponse).not.toBeNull();229 expect(createResponse.isSuccessful).toBeTruthy();230 });231 test('meeting repository - delete response 500', async () => {232 const meetingId = "fake-meeting-id";233 expect(validMeeting).not.toBeNull();234 const mockCollection1 = jest.fn(() => {235 return {236 withConverter: jest.fn(() => {237 throw new Error()238 }),239 doc: jest.fn(() => {240 throw new Error()241 }),242 where: jest.fn(() => {243 throw new Error()244 }),245 }246 });247 const mock = jest.fn().mockReturnValue({248 getStore: {249 collection: mockCollection1,250 },251 });252 const meeetingRepository = new MeetingsRepository(mock().getStore);253 expect(meeetingRepository).not.toBeNull();254 const createResponse = await meeetingRepository.delete(meetingId, "fake-user-id");255 expect(createResponse).not.toBeNull();256 expect(createResponse.isSuccessful).toBeFalsy();257 expect(createResponse.statusCode).toEqual(500);258 });...
CoreController.ts
Source:CoreController.ts
1// import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'2// import WalletService from "App/Features/Core/WalletManagement";3import BeneficiaryService from "App/Features/Core/BeneficiaryManagement";4import WalletService from "App/Features/Core/WalletManagement";5import PaymentService from "App/Features/Payment/PaymentManagement";6import CreatebeneficiaryValidator from "App/Validators/CreatebeneficiaryValidator";7import WalletFundingValidator from "App/Validators/WalletFundingValidator";8import WalletTransferValidator from "App/Validators/WalletTransferValidator";9import WalletWithdrawalValidator from "App/Validators/WalletWithdrawalValidator";10export default class CoreController {11 public async wallet_funding({ request, auth, response }) {12 const props = await request.validate(WalletFundingValidator);13 let createResponse = await PaymentService.initiate_payment(props, auth.user);14 return response15 .status(createResponse.status_code)16 .send(createResponse);17 }18 public async wallet_transfer({ request, auth, response }) {19 const props = await request.validate(WalletTransferValidator);20 let createResponse = await WalletService.transfer_money(props, auth.user);21 return response22 .status(createResponse.status_code)23 .send(createResponse);24 }25 public async wallet_withdrawal({ request, response, auth }) {26 // public async wallet_withdrawal({ request, auth, response }) {27 const props = await request.validate(WalletWithdrawalValidator);28 let createResponse = await WalletService.wallet_withdrawal(props, auth.user);29 // let createResponse = await WalletService.wallet_withdrawal(props, auth.user);30 return response31 .status(createResponse.status_code)32 .send(createResponse);33 }34 public async create_beneficiary({ request, auth, response }) {35 const props = await request.validate(CreatebeneficiaryValidator);36 let createResponse = await BeneficiaryService.create_beneficiary({ ...props, user_id: auth.user.id });37 return response38 .status(createResponse.status_code)39 .send(createResponse);40 }41 public async remove_beneficiary({ auth, response, params: { beneficiary_id } }) {42 let createResponse = await BeneficiaryService.remove_beneficiary(auth.user, beneficiary_id);43 return response44 .status(createResponse.status_code)45 .send(createResponse);46 }47 public async get_beneficiaries({ auth, response }) {48 let createResponse = await BeneficiaryService.get_beneficiaries(auth.user);49 return response50 .status(createResponse.status_code)51 .send(createResponse);52 }53 public async get_beneficiary({ auth, response, params: { beneficiary_id } }) {54 let createResponse = await BeneficiaryService.get_beneficiary(auth.user, beneficiary_id);55 return response56 .status(createResponse.status_code)57 .send(createResponse);58 }...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z7a8b9c0d1e2f3g4h5i6j7k8l9m0n1o2p3q4r5s6t7u8v9w0x1y2z3');3}, function (err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10var wpt = require('webpagetest');11var wpt = new WebPageTest('www.webpagetest.org', 'A.1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z7a8b9c0d1e2f3g4h5i6j7k8l9m0n1o2p3q4r5s6t7u8v9w0x1y2z3');12wpt.getLocations(function (err, data) {13 if (err) {14 console.log(err);15 } else {16 console.log(data);17 }18});19var wpt = require('webpagetest');20var wpt = new WebPageTest('www.webpagetest.org', 'A.1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z7a8b9c0d1e2f3g
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var options = {4};5wpt.createTest(options, function(err, data) {6 if (err) return console.error(err);7 console.log(data);8});9var wpt = require('webpagetest');10var wpt = new WebPageTest('www.webpagetest.org');11var options = {12};13wpt.createTest(options, function(err, data) {14 if (err) return console.error(err);15 console.log(data);16});17var wpt = require('webpagetest');18var wpt = new WebPageTest('www.webpagetest.org');19wpt.getLocations(function(err, data) {20 if (err) return console.error(err);21 console.log(data);22});23var wpt = require('webpagetest');24var wpt = new WebPageTest('www.webpagetest.org');25wpt.getTesters(function(err, data) {26 if (err) return console.error(err);27 console.log(data);28});29var wpt = require('webpagetest');30var wpt = new WebPageTest('www.webpagetest.org');31wpt.getTesters(function(err, data) {32 if (err) return console.error(err);33 console.log(data);34});35var wpt = require('webpagetest');36var wpt = new WebPageTest('www.webpagetest.org');37wpt.getTesters(function(err, data) {38 if (err) return console.error(err);39 console.log(data);40});
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log('data', data);5});6var wpt = require('webpagetest');7var wpt = new WebPageTest('www.webpagetest.org');8 if (err) return console.error(err);9 console.log('data', data);10});11var wpt = require('webpagetest');12var wpt = new WebPageTest('www.webpagetest.org');13wpt.getLocations(function(err, data) {14 if (err) return console.error(err);15 console.log('data', data);16});17var wpt = require('webpagetest');18var wpt = new WebPageTest('www.webpagetest.org');19wpt.getTesters(function(err, data) {20 if (err) return console.error(err);21 console.log('data', data);22});23var wpt = require('webpagetest');24var wpt = new WebPageTest('www.webpagetest.org');25 if (err) return console.error(err);26 console.log('data', data);27});28var wpt = require('webpagetest');29var wpt = new WebPageTest('www.webpagetest.org');30 if (err) return console.error(err);31 console.log('data', data);32});33var wpt = require('webpagetest');34var wpt = new WebPageTest('www.webpagetest.org');35 if (err) return console.error(err);36 console.log('data', data);37});
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if(err) console.log(err);4 else console.log(data);5});6var wpt = require('webpagetest');7var wpt = new WebPageTest('www.webpagetest.org');8 if(err) console.log(err);9 else console.log(data);10});11var wpt = require('webpagetest');12var wpt = new WebPageTest('www.webpagetest.org');13 if(err) console.log(err);14 else console.log(data);15});16var wpt = require('webpagetest');17var wpt = new WebPageTest('www.webpagetest.org');18 if(err) console.log(err);19 else console.log(data);20});21var wpt = require('webpagetest');22var wpt = new WebPageTest('www.webpagetest.org');23 if(err) console.log(err);24 else console.log(data);25});26var wpt = require('webpagetest');27var wpt = new WebPageTest('www.webpagetest.org');28 if(err) console.log(err);29 else console.log(data);30});31var wpt = require('webpagetest');32var wpt = new WebPageTest('www.webpagetest.org');33 if(err) console
Using AI Code Generation
1var wptools = require('wptools');2var wp = wptools.page('Barack Obama');3wp.createResponse(function(err, resp) {4 console.log(resp);5});6var wptools = require('wptools');7var wp = wptools.page('Barack Obama');8wp.createResponse(function(err, resp) {9 console.log(resp);10});11var wptools = require('wptools');12var wp = wptools.page('Barack Obama');13wp.createResponse(function(err, resp) {14 console.log(resp);15});16var wptools = require('wptools');17var wp = wptools.page('Barack Obama');18wp.createResponse(function(err, resp) {19 console.log(resp);20});21var wptools = require('wptools');22var wp = wptools.page('Barack Obama');23wp.createResponse(function(err, resp) {24 console.log(resp);25});26var wptools = require('wptools');27var wp = wptools.page('Barack Obama');28wp.createResponse(function(err, resp) {29 console.log(resp);30});31var wptools = require('wptools');32var wp = wptools.page('Barack Obama');33wp.createResponse(function(err, resp) {34 console.log(resp);35});36var wptools = require('wptools');37var wp = wptools.page('Barack Obama');38wp.createResponse(function(err, resp) {39 console.log(resp);40});41var wptools = require('wptools');42var wp = wptools.page('Barack Obama');43wp.createResponse(function(err, resp) {44 console.log(resp);45});
Using AI Code Generation
1const wpt = require('webpagetest');2const util = require('util');3const wptServer = 'www.webpagetest.org';4const wptTest = wpt(wptServer, process.env.WPT_API_KEY);5const testOptions = {6 videoParams: {7 },8};9wptTest.runTest(testUrl, testOptions, async (err, data) => {10 if (err) {11 console.log(err);12 } else {13 console.log('Test ID: ' + data.data.testId);14 console.log('View the test at: ' + data.data.userUrl);15 console.log('View the video at: ' + data.data.videoUrl);16 const testId = data.data.testId;17 const testResults = await util.promisify(wptTest.getTestResults)(18 );19 console.log('Test Results: ', testResults);20 }21});
Using AI Code Generation
1wpt.createResponse(function(err, response) {2 if(err) {3 console.error(err);4 } else {5 console.log(response);6 }7});8wpt.createResponse(function(err, response) {9 if(err) {10 console.error(err);11 } else {12 console.log(response);13 }14});15wpt.createResponse(function(err, response) {16 if(err) {17 console.error(err);18 } else {19 console.log(response);20 }21});22wpt.createResponse(function(err, response) {23 if(err) {24 console.error(err);25 } else {26 console.log(response);27 }28});29wpt.createResponse(function(err, response) {30 if(err) {31 console.error(err);32 } else {33 console.log(response);34 }35});36wpt.createResponse(function(err, response) {37 if(err) {38 console.error(err);39 } else {40 console.log(response);41 }42});43wpt.createResponse(function(err, response) {44 if(err) {45 console.error(err);46 } else {47 console.log(response);48 }49});50wpt.createResponse(function(err, response) {51 if(err) {52 console.error(err);53 } else {54 console.log(response);55 }56});57wpt.createResponse(function(err, response) {58 if(err) {59 console.error(err);60 } else {
Using AI Code Generation
1var wptools = require('wptools');2var wiki = wptools.page('Barack Obama');3wiki.createResponse(function(err, response){4 console.log(response)5});6{ title: 'Barack Obama',7 extract: 'Barack Hussein Obama II (US: /bəˈrɑːk huːˈseɪn oʊˈbɑːmə/; born August 4, 1961) is an American politician and attorney who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic Party, he was the first African American to be elected to the presidency. He previously served as a U.S. senator from Illinois from 2005 to 2008 and an Illinois state senator from 1997 to 2004. Obama was born in Honolulu, Hawaii. After graduating from Columbia University in 1983, he worked as a community organizer in Chicago. In 1988, he enrolled in Harvard Law School, where he was the first black president of the Harvard Law Review. After graduating, he became a civil rights attorney and professor, and taught constitutional law at the University of Chicago Law School from 1992 to 2004. He represented the 13th District for three terms in the Illinois Senate from 1997 to 2004, running unsuccessfully for the United States House of Representatives in 2000. He ran unsuccessfully in the Democratic primary for Illinois State Senate in 1996, losing to incumbent Alice Palmer. In 2004, Obama announced his campaign for the U.S. Senate seat being vacated by retiring Republican Peter Fitzgerald. He campaigned on a platform of reform, including ethics in government and government transparency, and was elected over Republican candidate Jack Ryan with 70% of the vote. He was reelected in 2010 with 70% of the vote. Obama was elected president in 2008, defeating Republican nominee John McCain. Eight years later, in 2016, he was elected to a second term, defeating Republican nominee Donald Trump. Obama was the first two-term U.S. president since Ronald Reagan and the first to have been elected to the presidency in consecutive elections since Franklin D. Roosevelt. He also
Using AI Code Generation
1var wptools = require('wptools');2var res = wptools.createResponse();3console.log(res);4res.setResponseCode(200);5console.log(res);6res.setResponseMessage('OK');7console.log(res);8res.setResponseData('Hello World');9console.log(res);10res.setResponseContentType('text/html');11console.log(res);12res.setResponseHeaders('{"Content-Type": "text/html"}');13console.log(res);14res.setResponseCookies('{"Content-Type": "text/html"}');15console.log(res);16res.setResponseSessionData('{"Content-Type": "text/html"}');17console.log(res);18res.setResponseRedirect('{"Content-Type": "text/html"}');19console.log(res);20res.setResponseStatus('{"Content-Type": "text/html"}');21console.log(res);22res.setResponse('{"Content-Type": "text/html"}');23console.log(res);24console.log(res.getResponseCode());25console.log(res.getResponseMessage());26console.log(res.getResponseData());27console.log(res.getResponseContentType());28console.log(res.getResponseHeaders());29console.log(res.getResponseCookies());30console.log(res.getResponseSessionData());31console.log(res.getResponseRedirect());32console.log(res.getResponseStatus());33console.log(res.getResponse());
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!