Best JavaScript code snippet using wpt
websocket-server.test.js
Source:websocket-server.test.js
1/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^ws$" }] */2'use strict';3const assert = require('assert');4const crypto = require('crypto');5const https = require('https');6const http = require('http');7const path = require('path');8const net = require('net');9const fs = require('fs');10const os = require('os');11const Sender = require('../lib/sender');12const WebSocket = require('../index');13const { NOOP } = require('../lib/constants');14describe('WebSocketServer', () => {15 describe('#ctor', () => {16 it('throws an error if no option object is passed', () => {17 assert.throws(18 () => new WebSocket.Server(),19 new RegExp(20 '^TypeError: One and only one of the "port", "server", or ' +21 '"noServer" options must be specified$'22 )23 );24 });25 describe('options', () => {26 it('throws an error if required options are not specified', () => {27 assert.throws(28 () => new WebSocket.Server({}),29 new RegExp(30 '^TypeError: One and only one of the "port", "server", or ' +31 '"noServer" options must be specified$'32 )33 );34 });35 it('throws an error if mutually exclusive options are specified', () => {36 const server = http.createServer();37 const variants = [38 { port: 0, noServer: true, server },39 { port: 0, noServer: true },40 { port: 0, server },41 { noServer: true, server }42 ];43 for (const options of variants) {44 assert.throws(45 () => new WebSocket.Server(options),46 new RegExp(47 '^TypeError: One and only one of the "port", "server", or ' +48 '"noServer" options must be specified$'49 )50 );51 }52 });53 it('exposes options passed to constructor', (done) => {54 const wss = new WebSocket.Server({ port: 0 }, () => {55 assert.strictEqual(wss.options.port, 0);56 wss.close(done);57 });58 });59 it('accepts the `maxPayload` option', (done) => {60 const maxPayload = 20480;61 const wss = new WebSocket.Server(62 {63 perMessageDeflate: true,64 maxPayload,65 port: 066 },67 () => {68 const ws = new WebSocket(`ws://localhost:${wss.address().port}`);69 ws.on('open', ws.close);70 }71 );72 wss.on('connection', (ws) => {73 assert.strictEqual(ws._receiver._maxPayload, maxPayload);74 assert.strictEqual(75 ws._receiver._extensions['permessage-deflate']._maxPayload,76 maxPayload77 );78 wss.close(done);79 });80 });81 });82 it('emits an error if http server bind fails', (done) => {83 const wss1 = new WebSocket.Server({ port: 0 }, () => {84 const wss2 = new WebSocket.Server({85 port: wss1.address().port86 });87 wss2.on('error', () => wss1.close(done));88 });89 });90 it('starts a server on a given port', (done) => {91 const port = 1337;92 const wss = new WebSocket.Server({ port }, () => {93 const ws = new WebSocket(`ws://localhost:${port}`);94 ws.on('open', ws.close);95 });96 wss.on('connection', () => wss.close(done));97 });98 it('binds the server on any IPv6 address when available', (done) => {99 const wss = new WebSocket.Server({ port: 0 }, () => {100 assert.strictEqual(wss._server.address().address, '::');101 wss.close(done);102 });103 });104 it('uses a precreated http server', (done) => {105 const server = http.createServer();106 server.listen(0, () => {107 const wss = new WebSocket.Server({ server });108 wss.on('connection', () => {109 server.close(done);110 });111 const ws = new WebSocket(`ws://localhost:${server.address().port}`);112 ws.on('open', ws.close);113 });114 });115 it('426s for non-Upgrade requests', (done) => {116 const wss = new WebSocket.Server({ port: 0 }, () => {117 http.get(`http://localhost:${wss.address().port}`, (res) => {118 let body = '';119 assert.strictEqual(res.statusCode, 426);120 res.on('data', (chunk) => {121 body += chunk;122 });123 res.on('end', () => {124 assert.strictEqual(body, http.STATUS_CODES[426]);125 wss.close(done);126 });127 });128 });129 });130 it('uses a precreated http server listening on unix socket', function (done) {131 //132 // Skip this test on Windows. The URL parser:133 //134 // - Throws an error if the named pipe uses backward slashes.135 // - Incorrectly parses the path if the named pipe uses forward slashes.136 //137 if (process.platform === 'win32') return this.skip();138 const server = http.createServer();139 const sockPath = path.join(140 os.tmpdir(),141 `ws.${crypto.randomBytes(16).toString('hex')}.sock`142 );143 server.listen(sockPath, () => {144 const wss = new WebSocket.Server({ server });145 wss.on('connection', (ws, req) => {146 if (wss.clients.size === 1) {147 assert.strictEqual(req.url, '/foo?bar=bar');148 } else {149 assert.strictEqual(req.url, '/');150 for (const client of wss.clients) {151 client.close();152 }153 server.close(done);154 }155 });156 const ws = new WebSocket(`ws+unix://${sockPath}:/foo?bar=bar`);157 ws.on('open', () => new WebSocket(`ws+unix://${sockPath}`));158 });159 });160 });161 describe('#address', () => {162 it('returns the address of the server', (done) => {163 const wss = new WebSocket.Server({ port: 0 }, () => {164 const addr = wss.address();165 assert.deepStrictEqual(addr, wss._server.address());166 wss.close(done);167 });168 });169 it('throws an error when operating in "noServer" mode', () => {170 const wss = new WebSocket.Server({ noServer: true });171 assert.throws(() => {172 wss.address();173 }, /^Error: The server is operating in "noServer" mode$/);174 });175 it('returns `null` if called after close', (done) => {176 const wss = new WebSocket.Server({ port: 0 }, () => {177 wss.close(() => {178 assert.strictEqual(wss.address(), null);179 done();180 });181 });182 });183 });184 describe('#close', () => {185 it('does not throw if called multiple times', (done) => {186 const wss = new WebSocket.Server({ port: 0 }, () => {187 wss.on('close', done);188 wss.close();189 wss.close();190 wss.close();191 });192 });193 it("doesn't close a precreated server", (done) => {194 const server = http.createServer();195 const realClose = server.close;196 server.close = () => {197 done(new Error('Must not close pre-created server'));198 };199 const wss = new WebSocket.Server({ server });200 wss.on('connection', () => {201 wss.close();202 server.close = realClose;203 server.close(done);204 });205 server.listen(0, () => {206 const ws = new WebSocket(`ws://localhost:${server.address().port}`);207 ws.on('open', ws.close);208 });209 });210 it('invokes the callback in noServer mode', (done) => {211 const wss = new WebSocket.Server({ noServer: true });212 wss.close(done);213 });214 it('cleans event handlers on precreated server', (done) => {215 const server = http.createServer();216 const wss = new WebSocket.Server({ server });217 server.listen(0, () => {218 wss.close(() => {219 assert.strictEqual(server.listenerCount('listening'), 0);220 assert.strictEqual(server.listenerCount('upgrade'), 0);221 assert.strictEqual(server.listenerCount('error'), 0);222 server.close(done);223 });224 });225 });226 it("emits the 'close' event after the server closes", (done) => {227 let serverCloseEventEmitted = false;228 const wss = new WebSocket.Server({ port: 0 }, () => {229 net.createConnection({ port: wss.address().port });230 });231 wss._server.on('connection', (socket) => {232 wss.close();233 //234 // The server is closing. Ensure this does not emit a `'close'`235 // event before the server is actually closed.236 //237 wss.close();238 process.nextTick(() => {239 socket.end();240 });241 });242 wss._server.on('close', () => {243 serverCloseEventEmitted = true;244 });245 wss.on('close', () => {246 assert.ok(serverCloseEventEmitted);247 done();248 });249 });250 it("emits the 'close' event if client tracking is disabled", (done) => {251 const wss = new WebSocket.Server({252 noServer: true,253 clientTracking: false254 });255 wss.on('close', done);256 wss.close();257 });258 it("emits the 'close' event if the server is already closed", (done) => {259 let callbackCalled = false;260 const wss = new WebSocket.Server({ port: 0 }, () => {261 wss.close(() => {262 assert.strictEqual(wss._state, 2);263 wss.on('close', () => {264 callbackCalled = true;265 });266 wss.close((err) => {267 assert.ok(callbackCalled);268 assert.ok(err instanceof Error);269 assert.strictEqual(err.message, 'The server is not running');270 done();271 });272 });273 });274 });275 });276 describe('#clients', () => {277 it('returns a list of connected clients', (done) => {278 const wss = new WebSocket.Server({ port: 0 }, () => {279 assert.strictEqual(wss.clients.size, 0);280 const ws = new WebSocket(`ws://localhost:${wss.address().port}`);281 ws.on('open', ws.close);282 });283 wss.on('connection', () => {284 assert.strictEqual(wss.clients.size, 1);285 wss.close(done);286 });287 });288 it('can be disabled', (done) => {289 const wss = new WebSocket.Server(290 { port: 0, clientTracking: false },291 () => {292 assert.strictEqual(wss.clients, undefined);293 const ws = new WebSocket(`ws://localhost:${wss.address().port}`);294 ws.on('open', () => ws.close());295 }296 );297 wss.on('connection', (ws) => {298 assert.strictEqual(wss.clients, undefined);299 ws.on('close', () => wss.close(done));300 });301 });302 it('is updated when client terminates the connection', (done) => {303 const wss = new WebSocket.Server({ port: 0 }, () => {304 const ws = new WebSocket(`ws://localhost:${wss.address().port}`);305 ws.on('open', () => ws.terminate());306 });307 wss.on('connection', (ws) => {308 ws.on('close', () => {309 assert.strictEqual(wss.clients.size, 0);310 wss.close(done);311 });312 });313 });314 it('is updated when client closes the connection', (done) => {315 const wss = new WebSocket.Server({ port: 0 }, () => {316 const ws = new WebSocket(`ws://localhost:${wss.address().port}`);317 ws.on('open', () => ws.close());318 });319 wss.on('connection', (ws) => {320 ws.on('close', () => {321 assert.strictEqual(wss.clients.size, 0);322 wss.close(done);323 });324 });325 });326 });327 describe('#shouldHandle', () => {328 it('returns true when the path matches', () => {329 const wss = new WebSocket.Server({ noServer: true, path: '/foo' });330 assert.strictEqual(wss.shouldHandle({ url: '/foo' }), true);331 assert.strictEqual(wss.shouldHandle({ url: '/foo?bar=baz' }), true);332 });333 it("returns false when the path doesn't match", () => {334 const wss = new WebSocket.Server({ noServer: true, path: '/foo' });335 assert.strictEqual(wss.shouldHandle({ url: '/bar' }), false);336 });337 });338 describe('#handleUpgrade', () => {339 it('can be used for a pre-existing server', (done) => {340 const server = http.createServer();341 server.listen(0, () => {342 const wss = new WebSocket.Server({ noServer: true });343 server.on('upgrade', (req, socket, head) => {344 wss.handleUpgrade(req, socket, head, (ws) => {345 ws.send('hello');346 ws.close();347 });348 });349 const ws = new WebSocket(`ws://localhost:${server.address().port}`);350 ws.on('message', (message, isBinary) => {351 assert.deepStrictEqual(message, Buffer.from('hello'));352 assert.ok(!isBinary);353 server.close(done);354 });355 });356 });357 it("closes the connection when path doesn't match", (done) => {358 const wss = new WebSocket.Server({ port: 0, path: '/ws' }, () => {359 const req = http.get({360 port: wss.address().port,361 headers: {362 Connection: 'Upgrade',363 Upgrade: 'websocket'364 }365 });366 req.on('response', (res) => {367 assert.strictEqual(res.statusCode, 400);368 wss.close(done);369 });370 });371 });372 it('closes the connection when protocol version is Hixie-76', (done) => {373 const wss = new WebSocket.Server({ port: 0 }, () => {374 const req = http.get({375 port: wss.address().port,376 headers: {377 Connection: 'Upgrade',378 Upgrade: 'WebSocket',379 'Sec-WebSocket-Key1': '4 @1 46546xW%0l 1 5',380 'Sec-WebSocket-Key2': '12998 5 Y3 1 .P00',381 'Sec-WebSocket-Protocol': 'sample'382 }383 });384 req.on('response', (res) => {385 assert.strictEqual(res.statusCode, 400);386 wss.close(done);387 });388 });389 });390 });391 describe('#completeUpgrade', () => {392 it('throws an error if called twice with the same socket', (done) => {393 const server = http.createServer();394 server.listen(0, () => {395 const wss = new WebSocket.Server({ noServer: true });396 server.on('upgrade', (req, socket, head) => {397 wss.handleUpgrade(req, socket, head, (ws) => {398 ws.close();399 });400 assert.throws(401 () => wss.handleUpgrade(req, socket, head, NOOP),402 (err) => {403 assert.ok(err instanceof Error);404 assert.strictEqual(405 err.message,406 'server.handleUpgrade() was called more than once with the ' +407 'same socket, possibly due to a misconfiguration'408 );409 return true;410 }411 );412 });413 const ws = new WebSocket(`ws://localhost:${server.address().port}`);414 ws.on('open', () => {415 ws.on('close', () => {416 server.close(done);417 });418 });419 });420 });421 });422 describe('Connection establishing', () => {423 it('fails if the Sec-WebSocket-Key header is invalid (1/2)', (done) => {424 const wss = new WebSocket.Server({ port: 0 }, () => {425 const req = http.get({426 port: wss.address().port,427 headers: {428 Connection: 'Upgrade',429 Upgrade: 'websocket'430 }431 });432 req.on('response', (res) => {433 assert.strictEqual(res.statusCode, 400);434 wss.close(done);435 });436 });437 wss.on('connection', () => {438 done(new Error("Unexpected 'connection' event"));439 });440 });441 it('fails if the Sec-WebSocket-Key header is invalid (2/2)', (done) => {442 const wss = new WebSocket.Server({ port: 0 }, () => {443 const req = http.get({444 port: wss.address().port,445 headers: {446 Connection: 'Upgrade',447 Upgrade: 'websocket',448 'Sec-WebSocket-Key': 'P5l8BJcZwRc='449 }450 });451 req.on('response', (res) => {452 assert.strictEqual(res.statusCode, 400);453 wss.close(done);454 });455 });456 wss.on('connection', () => {457 done(new Error("Unexpected 'connection' event"));458 });459 });460 it('fails if the Sec-WebSocket-Version header is invalid (1/2)', (done) => {461 const wss = new WebSocket.Server({ port: 0 }, () => {462 const req = http.get({463 port: wss.address().port,464 headers: {465 Connection: 'Upgrade',466 Upgrade: 'websocket',467 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ=='468 }469 });470 req.on('response', (res) => {471 assert.strictEqual(res.statusCode, 400);472 wss.close(done);473 });474 });475 wss.on('connection', () => {476 done(new Error("Unexpected 'connection' event"));477 });478 });479 it('fails if the Sec-WebSocket-Version header is invalid (2/2)', (done) => {480 const wss = new WebSocket.Server({ port: 0 }, () => {481 const req = http.get({482 port: wss.address().port,483 headers: {484 Connection: 'Upgrade',485 Upgrade: 'websocket',486 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',487 'Sec-WebSocket-Version': 12488 }489 });490 req.on('response', (res) => {491 assert.strictEqual(res.statusCode, 400);492 wss.close(done);493 });494 });495 wss.on('connection', () => {496 done(new Error("Unexpected 'connection' event"));497 });498 });499 it('fails is the Sec-WebSocket-Protocol header is invalid', (done) => {500 const wss = new WebSocket.Server({ port: 0 }, () => {501 const req = http.get({502 port: wss.address().port,503 headers: {504 Connection: 'Upgrade',505 Upgrade: 'websocket',506 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',507 'Sec-WebSocket-Version': 13,508 'Sec-WebSocket-Protocol': 'foo;bar'509 }510 });511 req.on('response', (res) => {512 assert.strictEqual(res.statusCode, 400);513 wss.close(done);514 });515 });516 wss.on('connection', () => {517 done(new Error("Unexpected 'connection' event"));518 });519 });520 it('fails if the Sec-WebSocket-Extensions header is invalid', (done) => {521 const wss = new WebSocket.Server(522 {523 perMessageDeflate: true,524 port: 0525 },526 () => {527 const req = http.get({528 port: wss.address().port,529 headers: {530 Connection: 'Upgrade',531 Upgrade: 'websocket',532 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',533 'Sec-WebSocket-Version': 13,534 'Sec-WebSocket-Extensions':535 'permessage-deflate; server_max_window_bits=foo'536 }537 });538 req.on('response', (res) => {539 assert.strictEqual(res.statusCode, 400);540 wss.close(done);541 });542 }543 );544 wss.on('connection', () => {545 done(new Error("Unexpected 'connection' event"));546 });547 });548 it('fails if the WebSocket server is closing or closed', (done) => {549 const server = http.createServer();550 const wss = new WebSocket.Server({ noServer: true });551 server.on('upgrade', (req, socket, head) => {552 wss.close();553 wss.handleUpgrade(req, socket, head, () => {554 done(new Error('Unexpected callback invocation'));555 });556 });557 server.listen(0, () => {558 const ws = new WebSocket(`ws://localhost:${server.address().port}`);559 ws.on('unexpected-response', (req, res) => {560 assert.strictEqual(res.statusCode, 503);561 res.resume();562 server.close(done);563 });564 });565 });566 it('handles unsupported extensions', (done) => {567 const wss = new WebSocket.Server(568 {569 perMessageDeflate: true,570 port: 0571 },572 () => {573 const req = http.get({574 port: wss.address().port,575 headers: {576 Connection: 'Upgrade',577 Upgrade: 'websocket',578 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',579 'Sec-WebSocket-Version': 13,580 'Sec-WebSocket-Extensions': 'foo; bar'581 }582 });583 req.on('upgrade', (res, socket, head) => {584 if (head.length) socket.unshift(head);585 socket.once('data', (chunk) => {586 assert.strictEqual(chunk[0], 0x88);587 socket.destroy();588 wss.close(done);589 });590 });591 }592 );593 wss.on('connection', (ws) => {594 assert.strictEqual(ws.extensions, '');595 ws.close();596 });597 });598 describe('`verifyClient`', () => {599 it('can reject client synchronously', (done) => {600 const wss = new WebSocket.Server(601 {602 verifyClient: () => false,603 port: 0604 },605 () => {606 const req = http.get({607 port: wss.address().port,608 headers: {609 Connection: 'Upgrade',610 Upgrade: 'websocket',611 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',612 'Sec-WebSocket-Version': 8613 }614 });615 req.on('response', (res) => {616 assert.strictEqual(res.statusCode, 401);617 wss.close(done);618 });619 }620 );621 wss.on('connection', () => {622 done(new Error("Unexpected 'connection' event"));623 });624 });625 it('can accept client synchronously', (done) => {626 const server = https.createServer({627 cert: fs.readFileSync('test/fixtures/certificate.pem'),628 key: fs.readFileSync('test/fixtures/key.pem')629 });630 const wss = new WebSocket.Server({631 verifyClient: (info) => {632 assert.strictEqual(info.origin, 'https://example.com');633 assert.strictEqual(info.req.headers.foo, 'bar');634 assert.ok(info.secure, true);635 return true;636 },637 server638 });639 wss.on('connection', () => {640 server.close(done);641 });642 server.listen(0, () => {643 const ws = new WebSocket(`wss://localhost:${server.address().port}`, {644 headers: { Origin: 'https://example.com', foo: 'bar' },645 rejectUnauthorized: false646 });647 ws.on('open', ws.close);648 });649 });650 it('can accept client asynchronously', (done) => {651 const wss = new WebSocket.Server(652 {653 verifyClient: (o, cb) => process.nextTick(cb, true),654 port: 0655 },656 () => {657 const ws = new WebSocket(`ws://localhost:${wss.address().port}`);658 ws.on('open', ws.close);659 }660 );661 wss.on('connection', () => wss.close(done));662 });663 it('can reject client asynchronously', (done) => {664 const wss = new WebSocket.Server(665 {666 verifyClient: (info, cb) => process.nextTick(cb, false),667 port: 0668 },669 () => {670 const req = http.get({671 port: wss.address().port,672 headers: {673 Connection: 'Upgrade',674 Upgrade: 'websocket',675 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',676 'Sec-WebSocket-Version': 8677 }678 });679 req.on('response', (res) => {680 assert.strictEqual(res.statusCode, 401);681 wss.close(done);682 });683 }684 );685 wss.on('connection', () => {686 done(new Error("Unexpected 'connection' event"));687 });688 });689 it('can reject client asynchronously w/ status code', (done) => {690 const wss = new WebSocket.Server(691 {692 verifyClient: (info, cb) => process.nextTick(cb, false, 404),693 port: 0694 },695 () => {696 const req = http.get({697 port: wss.address().port,698 headers: {699 Connection: 'Upgrade',700 Upgrade: 'websocket',701 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',702 'Sec-WebSocket-Version': 8703 }704 });705 req.on('response', (res) => {706 assert.strictEqual(res.statusCode, 404);707 wss.close(done);708 });709 }710 );711 wss.on('connection', () => {712 done(new Error("Unexpected 'connection' event"));713 });714 });715 it('can reject client asynchronously w/ custom headers', (done) => {716 const wss = new WebSocket.Server(717 {718 verifyClient: (info, cb) => {719 process.nextTick(cb, false, 503, '', { 'Retry-After': 120 });720 },721 port: 0722 },723 () => {724 const req = http.get({725 port: wss.address().port,726 headers: {727 Connection: 'Upgrade',728 Upgrade: 'websocket',729 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',730 'Sec-WebSocket-Version': 8731 }732 });733 req.on('response', (res) => {734 assert.strictEqual(res.statusCode, 503);735 assert.strictEqual(res.headers['retry-after'], '120');736 wss.close(done);737 });738 }739 );740 wss.on('connection', () => {741 done(new Error("Unexpected 'connection' event"));742 });743 });744 });745 it("doesn't emit the 'connection' event if socket is closed prematurely", (done) => {746 const server = http.createServer();747 server.listen(0, () => {748 const wss = new WebSocket.Server({749 verifyClient: ({ req: { socket } }, cb) => {750 assert.strictEqual(socket.readable, true);751 assert.strictEqual(socket.writable, true);752 socket.on('end', () => {753 assert.strictEqual(socket.readable, false);754 assert.strictEqual(socket.writable, true);755 cb(true);756 });757 },758 server759 });760 wss.on('connection', () => {761 done(new Error("Unexpected 'connection' event"));762 });763 const socket = net.connect(764 {765 port: server.address().port,766 allowHalfOpen: true767 },768 () => {769 socket.end(770 [771 'GET / HTTP/1.1',772 'Host: localhost',773 'Upgrade: websocket',774 'Connection: Upgrade',775 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==',776 'Sec-WebSocket-Version: 13',777 '\r\n'778 ].join('\r\n')779 );780 }781 );782 socket.on('end', () => {783 wss.close();784 server.close(done);785 });786 });787 });788 it('handles data passed along with the upgrade request', (done) => {789 const wss = new WebSocket.Server({ port: 0 }, () => {790 const req = http.request({791 port: wss.address().port,792 headers: {793 Connection: 'Upgrade',794 Upgrade: 'websocket',795 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',796 'Sec-WebSocket-Version': 13797 }798 });799 const list = Sender.frame(Buffer.from('Hello'), {800 fin: true,801 rsv1: false,802 opcode: 0x01,803 mask: true,804 readOnly: false805 });806 req.write(Buffer.concat(list));807 req.end();808 });809 wss.on('connection', (ws) => {810 ws.on('message', (data, isBinary) => {811 assert.deepStrictEqual(data, Buffer.from('Hello'));812 assert.ok(!isBinary);813 wss.close(done);814 });815 });816 });817 describe('`handleProtocols`', () => {818 it('allows to select a subprotocol', (done) => {819 const handleProtocols = (protocols, request) => {820 assert.ok(request instanceof http.IncomingMessage);821 assert.strictEqual(request.url, '/');822 return Array.from(protocols).pop();823 };824 const wss = new WebSocket.Server({ handleProtocols, port: 0 }, () => {825 const ws = new WebSocket(`ws://localhost:${wss.address().port}`, [826 'foo',827 'bar'828 ]);829 ws.on('open', () => {830 assert.strictEqual(ws.protocol, 'bar');831 wss.close(done);832 });833 });834 wss.on('connection', (ws) => {835 ws.close();836 });837 });838 });839 it("emits the 'headers' event", (done) => {840 const wss = new WebSocket.Server({ port: 0 }, () => {841 const ws = new WebSocket(`ws://localhost:${wss.address().port}`);842 ws.on('open', ws.close);843 });844 wss.on('headers', (headers, request) => {845 assert.deepStrictEqual(headers.slice(0, 3), [846 'HTTP/1.1 101 Switching Protocols',847 'Upgrade: websocket',848 'Connection: Upgrade'849 ]);850 assert.ok(request instanceof http.IncomingMessage);851 assert.strictEqual(request.url, '/');852 wss.on('connection', () => wss.close(done));853 });854 });855 });856 describe('permessage-deflate', () => {857 it('is disabled by default', (done) => {858 const wss = new WebSocket.Server({ port: 0 }, () => {859 const ws = new WebSocket(`ws://localhost:${wss.address().port}`);860 ws.on('open', ws.close);861 });862 wss.on('connection', (ws, req) => {863 assert.strictEqual(864 req.headers['sec-websocket-extensions'],865 'permessage-deflate; client_max_window_bits'866 );867 assert.strictEqual(ws.extensions, '');868 wss.close(done);869 });870 });871 it('uses configuration options', (done) => {872 const wss = new WebSocket.Server(873 {874 perMessageDeflate: { clientMaxWindowBits: 8 },875 port: 0876 },877 () => {878 const ws = new WebSocket(`ws://localhost:${wss.address().port}`);879 ws.on('upgrade', (res) => {880 assert.strictEqual(881 res.headers['sec-websocket-extensions'],882 'permessage-deflate; client_max_window_bits=8'883 );884 wss.close(done);885 });886 }887 );888 wss.on('connection', (ws) => {889 ws.close();890 });891 });892 });...
testing.ts
Source:testing.ts
1// Copyright 2017-2021 @polkadot/apps-config authors & contributors2// SPDX-License-Identifier: Apache-2.03import type { TFunction } from 'i18next';4import type { LinkOption } from '../settings/types';5import { createRococo } from './testingRococo';6import { expandEndpoints } from './util';7/* eslint-disable sort-keys */8// The available endpoints that will show in the dropdown. For the most part (with the exception of9// Polkadot) we try to keep this to live chains only, with RPCs hosted by the community/chain vendor10// info: The chain logo name as defined in ../ui/logos/index.ts in namedLogos (this also needs to align with @polkadot/networks)11// text: The text to display on the dropdown12// value: The actual hosted secure websocket endpoint13export function createTesting(t: TFunction): LinkOption[] {14 return expandEndpoints(t, [15 {16 info: 'automata',17 text: t('rpc.automata', 'Automata', { ns: 'apps-config' }),18 providers: {19 Automata: 'wss://api.ata.network'20 }21 },22 // polkadot test relays23 createRococo(t),24 // alphabetical based on chain name25 {26 info: 'centrifuge',27 text: t('rpc.amber', 'Amber', { ns: 'apps-config' }),28 providers: {29 Centrifuge: 'wss://fullnode.amber.centrifuge.io'30 }31 },32 {33 info: 'nodle',34 text: t('rpc.nodle-arcadia', 'Arcadia', { ns: 'apps-config' }),35 providers: {36 Nodle: 'wss://arcadia1.nodleprotocol.io'37 }38 },39 {40 info: 'edgeware',41 text: t('rpc.beresheet', 'Beresheet', { ns: 'apps-config' }),42 providers: {43 'Commonwealth Labs': 'wss://beresheet1.edgewa.re'44 }45 },46 {47 info: 'bitcountry',48 text: t('rpc.bitcountry', 'Bit.Country Tewai', { ns: 'apps-config' }),49 providers: {50 'Bit.Country': 'wss://whenua.bit.country'51 }52 },53 {54 info: 'bifrost',55 text: t('rpc.bifrost', 'Bifrost Asgard', { ns: 'apps-config' }),56 providers: {57 Bifrost: 'wss://testnet.liebi.com'58 }59 },60 {61 info: 'canvas',62 text: t('rpc.canvas', 'Canvas', { ns: 'apps-config' }),63 providers: {64 Parity: 'wss://canvas-rpc.parity.io'65 }66 },67 {68 info: 'clover',69 text: t('rpc.clover.finance', 'Clover', { ns: 'apps-config' }),70 providers: {71 Clover: 'wss://api.clover.finance/'72 }73 },74 {75 info: 'crust',76 text: t('rpc.crust.network', 'Crust Maxwell', { ns: 'apps-config' }),77 providers: {78 'Crust Network': 'wss://api.crust.network/'79 }80 },81 {82 info: 'datahighway',83 isDisabled: true,84 text: t('rpc.datahighway.harbour', 'Harbour', { ns: 'apps-config' }),85 providers: {86 MXC: 'wss://testnet-harbour.datahighway.com'87 }88 },89 {90 info: 'dock-testnet',91 text: t('rpc.dock-testnet', 'Dock', { ns: 'apps-config' }),92 providers: {93 'Dock Association': 'wss://danforth-1.dock.io'94 }95 },96 {97 info: 'dusty',98 text: t('rpc.dusty', 'Dusty', { ns: 'apps-config' }),99 providers: {100 'Stake Technologies': 'wss://rpc.dusty.plasmnet.io/'101 }102 },103 {104 info: 'encointer_cantillon',105 text: t('rpc.encointer.cantillon', 'Encointer Cantillon', { ns: 'apps-config' }),106 providers: {107 'Encointer Association': 'wss://cantillon.encointer.org'108 }109 },110 {111 info: 'encointer_gesell',112 text: t('rpc.encointer.gesell', 'Encointer Gesell', { ns: 'apps-config' }),113 providers: {114 'Encointer Association': 'wss://gesell.encointer.org'115 }116 },117 {118 info: 'equilibrium',119 text: t('rpc.equilibriumtestnet', 'Equilibrium', { ns: 'apps-config' }),120 providers: {121 Equilibrium: 'wss://api.mvp.testnet.equilibrium.io'122 }123 },124 {125 info: 'substrate',126 text: t('rpc.flamingfir', 'Flaming Fir', { ns: 'apps-config' }),127 providers: {128 Parity: 'wss://substrate-rpc.parity.io'129 }130 },131 {132 info: 'galois',133 text: t('rpc.galois', 'Galois', { ns: 'apps-config' }),134 providers: {135 MathWallet: 'wss://galois.maiziqianbao.net/ws'136 }137 },138 {139 info: 'jupiter',140 text: t('rpc.jupiter', 'Jupiter', { ns: 'apps-config' }),141 providers: {142 Elara: 'wss://jupiter.elara.patract.io'143 }144 },145 {146 info: 'jupiter',147 text: t('rpc.jupiter', 'Jupiter', { ns: 'apps-config' }),148 providers: {149 Patract: 'wss://ws.jupiter.patract.cn'150 }151 },152 {153 info: 'acala',154 text: t('rpc.mandala', 'Mandala', { ns: 'apps-config' }),155 providers: {156 Acala: 'wss://node-6714447553211260928.rz.onfinality.io/ws',157 'Patract Elara': 'wss://mandala.elara.patract.io'158 }159 },160 {161 info: 'kilt',162 text: t('rpc.kilt', 'Mashnet', { ns: 'apps-config' }),163 providers: {164 'KILT Protocol': 'wss://full-nodes.kilt.io:9944/'165 }166 },167 {168 info: 'moonbaseAlpha',169 text: t('rpc.moonbeam', 'Moonbase Alpha', { ns: 'apps-config' }),170 providers: {171 'Moonbeam Network': 'wss://wss.testnet.moonbeam.network'172 }173 },174 {175 info: 'phala',176 text: t('rpc.phala', 'Phala PoC-3', { ns: 'apps-config' }),177 providers: {178 'Phala Network': 'wss://poc3a.phala.network/ws'179 }180 },181 {182 info: 'polkadex',183 text: t('rpc.polkadex', 'Polkadex', { ns: 'apps-config' }),184 providers: {185 'Polkadex Team': 'wss://blockchain.polkadex.trade'186 }187 },188 {189 info: 'polkabtc',190 text: t('rpc.polkabtc', 'PolkaBTC', { ns: 'apps-config' }),191 providers: {192 Interlay: 'wss://alpha.polkabtc.io/api/parachain'193 }194 },195 {196 info: 'laminar',197 text: t('rpc.turbulence', 'Turbulence', { ns: 'apps-config' }),198 providers: {199 Laminar: 'wss://testnet-node-1.laminar-chain.laminar.one/ws'200 }201 },202 {203 info: 'sora-substrate',204 text: t('rpc.sora-substrate', 'SORA-staging', { ns: 'apps-config' }),205 providers: {206 Soramitsu: 'wss://ws.stage.sora2.soramitsu.co.jp'207 }208 },209 {210 info: 'ternoa-chaos',211 text: t('rpc.ternoa-chaos', 'Ternoa Chaos', { ns: 'apps-config' }),212 providers: {213 CapsuleCorp: 'wss://chaos.ternoa.com'214 }215 },216 {217 dnslink: 'westend',218 info: 'westend',219 text: t('rpc.westend', 'Westend', { ns: 'apps-config' }),220 providers: {221 Parity: 'wss://westend-rpc.polkadot.io'222 }223 },224 {225 info: 'zero',226 text: t('rpc.zero', 'Zero', { ns: 'apps-config' }),227 providers: {228 ZERO: 'wss://alphaville-0.zero.io'229 }230 },231 {232 info: 'uniarts',233 text: t('rpc.uniarts', 'Uniarts', { ns: 'apps-config' }),234 providers: {235 Uniarts: 'wss://testnet.uniarts.me'236 }237 }238 ]);...
allFn.js
Source:allFn.js
1//ç»é æµè¯æå2login=()=>{3 const user = {4 "astrAccountName": "dzk",5 "astrUserPassWord": "123"6 };7 const srtUser = JSON.stringify(user);8 const action = {9 "FromUser": "",10 "Tag": "ac",11 "Message": srtUser,12 "ActionMethod": "UserBLL.Login"13 };14 var wss=new WebSocket("ws://172.16.31.250:9009/");15 wss.onopen=function () {16 wss.send(JSON.stringify(action))17 };18 wss.onmessage=function (ev) {19 alert(ev.data);20 }21};22//æ¥è¯¢å¨æ¥æå
çèµäº æµè¯æå23selectDateMatch=()=>{24 var date={25 'aDate':'2019-5-30'26 };27 const srt = JSON.stringify(date);28 const action = {29 "FromUser": "",30 "Tag": "ac",31 "Message": srt,32 "ActionMethod":"CompetitionBLL.GetComprtitionByDate"33 };34 var wss=new WebSocket("ws://172.16.31.250:9009/");35 wss.onopen=function () {36 wss.send(JSON.stringify(action))37 };38 wss.onmessage=function (ev) {39 alert(ev.data);40 }41};42//æ¥è¯¢è¦è¿è¡å¾çè½®æçèµäº æµè¯æå43selectSwipeMatch=()=>{44 const action = {45 "FromUser": "",46 "Tag": "ac",47 "Message": "null",48 "ActionMethod":"CompetitionBLL.GetCompetitionByCarousel"49 };50 var wss=new WebSocket("ws://172.16.31.250:9009/");51 wss.onopen=function () {52 wss.send(JSON.stringify(action))53 };54 wss.onmessage=function (ev) {55 console.log(ev.data);56 }57};58//æ¥è¯¢è¦å¨é¦é¡µå±ç¤ºçèµäº æµè¯æå59selectIndexMatch=()=>{60 const action = {61 "FromUser": "",62 "Tag": "ac",63 "Message": "null",64 "ActionMethod":"CompetitionBLL.GetCompetitionByIndex"65 };66 var wss=new WebSocket("ws://172.16.31.250:9009/");67 wss.onopen=function () {68 wss.send(JSON.stringify(action))69 };70 wss.onmessage=function (ev) {71 console.log(ev.data);72 }73};74//æ¥è¯¢è¯¥èµäºçç©æ³ åç©æ³çæç¥¨ä¿¡æ¯ æµè¯æå75selectMatchInfo=()=>{76 const data={77 "aintComprtitionID":4,78 "astrAccountName":"dzk"79 };80 const str=JSON.stringify(data);81 const action = {82 "FromUser": "",83 "Tag": "ac",84 "Message": str,85 "ActionMethod":"GameMethodBLL.GetCompetitionMethod"86 };87 var wss=new WebSocket("ws://172.16.31.250:9009/");88 wss.onopen=function () {89 wss.send(JSON.stringify(action))90 };91 wss.onmessage=function (ev) {92 console.log(ev.data);93 }94};95//æ·»å ä¸æ¡æ票 æµè¯æå96addOneVote=()=>{97 const data={98 "AccountName":"dzk",99 "MethodID":2,100 "CompetitionID":4101 };102 const str=JSON.stringify(data);103 const action = {104 "FromUser": "",105 "Tag": "ac",106 "Message": str,107 "ActionMethod":"BetBLL.InsertBet"108 };109 var wss=new WebSocket("ws://172.16.31.250:9009/");110 wss.onopen=function () {111 wss.send(JSON.stringify(action))112 };113 wss.onmessage=function (ev) {114 console.log(ev.data);115 }...
Using AI Code Generation
1var wpt = require('webpagetest');2var wss = new wpt('www.webpagetest.org');3wss.runTest('www.google.com', function(err, data) {4 if (err) return console.error(err);5 console.log(data);6});7var wpt = require('webpagetest');8var wss = new wpt('www.webpagetest.org');9var options = {10};11wss.runTest('www.google.com', options, function(err, data) {12 if (err) return console.error(err);13 console.log(data);14});15var wpt = require('webpagetest');16var wss = new wpt('www.webpagetest.org');17var options = {18};19function callback(err, data) {20 if (err) return console.error(err);21 console.log(data);22}23wss.runTest('www.google.com', options, callback);24var wpt = require('webpagetest');25var wss = new wpt('www.webpagetest.org');26var options = {27};28function callback(err, data) {29 if (err) return console.error(err);30 console.log(data);31}32wss.runTest('www.google.com', options, callback, 'testId');33var wpt = require('webpagetest');34var wss = new wpt('www.webpagetest.org');35var options = {36};37function callback(err, data) {38 if (err) return console.error(err
Using AI Code Generation
1var wss = require("wptoolkit").wss;2var wss = require("wptoolkit").wss;3var wss = require("wptoolkit").wss;4var wss = require("wptoolkit").wss;5var wss = require("wptoolkit").wss;6var wss = require("wptoolkit").wss;7var wss = require("wptoolkit").wss;8var wss = require("wptoolkit").wss;9var wss = require("wptoolkit").wss;10var wss = require("wptoolkit").wss;11var wss = require("wptoolkit").wss;12var wss = require("wptoolkit").wss;13var wss = require("wptoolkit").wss;14var wss = require("wptoolkit").wss;15 if (err) {16 console.log(err);17 } else {18 console.log(res);19 }20});21### `wss.get(url, callback)`
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const path = require('path');4const { promisify } = require('util');5const writeFile = promisify(fs.writeFile);6async function getWikipediaInfo() {7 const page = wptools.page('Rajesh Khanna', { format: 'json' });8 const result = await page.get();9 const data = JSON.stringify(result);10 await writeFile(path.resolve(__dirname, 'data.json'), data);11}12getWikipediaInfo();13MIT © [Ankit Jain](
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const path = require('path');4const config = require('./config');5const { exec } = require('child_process');6const getWikiPage = (pageName) => {7 return new Promise((resolve, reject) => {8 wptools.page(pageName, { format: 'json' })9 .then((page) => {10 page.get((err, info) => {11 if (err) {12 reject(err);13 } else {14 resolve(info);15 }16 });17 })18 .catch((err) => {19 reject(err);20 });21 });22};23const getWikiPageWithWss = (pageName) => {24 return new Promise((resolve, reject) => {25 wptools.page(pageName, { format: 'json' })26 .then((page) => {27 page.get((err, info) => {28 if (err) {29 reject(err);30 } else {31 resolve(info);32 }33 });34 })35 .catch((err) => {36 reject(err);37 });38 });39};40const saveImage = (url, pageName) => {41 return new Promise((resolve, reject) => {42 const filePath = path.join(config.imagePath, `${pageName}.jpg`);43 exec(`wget ${url} -O ${filePath}`, (err, stdout, stderr) => {44 if (err) {45 reject(err);46 return;47 }48 resolve(filePath);49 });50 });51};52const getWikiPageAndSaveImage = async (pageName) => {53 try {54 const info = await getWikiPage(pageName);55 const url = info.image[0].url;56 const filePath = await saveImage(url, pageName);57 return filePath;58 } catch (err) {59 console.log(err);60 }61};62const getWikiPageAndSaveImageWithWss = async (pageName) => {63 try {64 const info = await getWikiPageWithWss(pageName);65 const url = info.image[0].url;66 const filePath = await saveImage(url, pageName);67 return filePath;68 } catch (err) {69 console.log(err);70 }71};72const test = async () => {73 try {74 const filePath = await getWikiPageAndSaveImageWithWss('Albert Einstein');
Using AI Code Generation
1var wptools = require('wptools');2wptools.page('Albert Einstein').then(function(page) {3 return page.getWikiText();4}).then(function(text) {5 console.log(text);6});7var wptools = require('wptools');8wptools.page('Albert Einstein').then(function(page) {9 return page.getWikiText();10}).then(function(text) {11 console.log(text);12});13var wptools = require('wptools');14wptools.page('Albert Einstein').then(function(page) {15 return page.getWikiText();16}).then(function(text) {17 console.log(text);18});19var wptools = require('wptools');20wptools.page('Albert Einstein').then(function(page) {21 return page.getWikiText();22}).then(function(text) {23 console.log(text);24});25var wptools = require('wptools');26wptools.page('Albert Einstein').then(function(page) {27 return page.getWikiText();28}).then(function(text) {29 console.log(text);30});31var wptools = require('wptools');32wptools.page('Albert Einstein').then(function(page) {33 return page.getWikiText();34}).then(function(text) {35 console.log(text);36});37var wptools = require('wptools');38wptools.page('Albert Einstein').then(function(page) {39 return page.getWikiText();40}).then(function(text) {41 console.log(text);42});43var wptools = require('wptools');44wptools.page('Albert Einstein').then(function(page) {45 return page.getWikiText();46}).then(function(text) {47 console.log(text);48});49var wptools = require('wptools');50wptools.page('Albert Einstein').then(function(page) {51 return page.getWikiText();52}).then(function(text) {53 console.log(text);54});55var wptools = require('wptools');56wptools.page('Albert Einstein').then(function(page) {57 return page.getWikiText();58}).then(function(text) {59 console.log(text);60});61var wptools = require('wptools');62wptools.page('Albert Einstein').then
Using AI Code Generation
1var wptoolkit = require('wptoolkit');2var wss = new wptoolkit.wss();3wss.getWeather('New York', function (err, data) {4 console.log(data);5});6var wptoolkit = require('wptoolkit');7var wss = new wptoolkit.wss();8wss.getWeather('New York', function (err, data) {9 console.log(data);10});11## wss.getWeather(location, callback)12var wptoolkit = require('wptoolkit');13var wss = new wptoolkit.wss();14wss.getWeather('New York', function (err, data) {15 console.log(data);16});17## wss.getWeatherByCoordinates(latitude, longitude, callback)18var wptoolkit = require('wptoolkit');19var wss = new wptoolkit.wss();20wss.getWeatherByCoordinates(40.7143528, -74.0059731, function (err, data) {21 console.log(data);22});23## wss.getWeatherByZip(zipCode, callback)
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const data = fs.readFileSync('test.json');4const obj = JSON.parse(data);5const pages = obj.pages;6for (var i = 0; i < pages.length; i++) {7 var page = pages[i];8 var title = page.title;9 var pageid = page.pageid;10 var fullurl = page.fullurl;11 var extract = page.extract;12 var wiki = new wptools.page(title, { format: 'json' });13 wiki.get_infobox(function (err, info) {14 if (err) {15 console.log(err);16 }17 else {18 console.log(info);19 }20 });21}22{23 "continue": {24 },25 "query": {26 "searchinfo": {27 },28 {29 "snippet": "<span class=\"searchmatch\">Pokémon</span> (Japanese: <span class=\"searchmatch\">ポケモン</span> (<span class=\"searchmatch\">Pokémon</span>), English: /ˈpoʊkeɪmɒn/ or /ˈpoʊkɪmɒn/) are creatures of all shapes and sizes that inhabit the world of the <span class=\"searchmatch\">Pokémon</span> games. They can be caught using Pok
Using AI Code Generation
1var wpt = require('webpagetest');2var options = {3};4var wpt = new WebPageTest('www.webpagetest.org', 'A.1d4b4c4a0c9e9d2a2b2a2b2a2b2a2b2a');5wpt.runTest(testURL, function(err, data) {6 if (err) return console.error(err);7 console.log(data);8});
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!!