How to use _parseRequest method in Playwright Internal

Best JavaScript code snippet using playwright-internal

WebhookServer.js

Source:WebhookServer.js Github

copy

Full Screen

...284 log.mock((msg, status) => {285 expect(msg).to.match(/Error for route type github: Invalid headers/i);286 expect(status).to.equal(2);287 });288 expect(() => whs._parseRequest(req, route))289 .to.throw(/Error for route type github: Invalid headers/);290 expect(log.count).to.equal(1);291 log.checkMocks();292 });293 it('throws if unknown type', () => {294 let route = {295 type: 'nope'296 };297 let req = {298 headers: {}299 };300 log.mock((msg, status) => {301 expect(msg).to.match(/Error unknown route type nope/i);302 expect(status).to.equal(2);303 });304 expect(() => whs._parseRequest(req, route))305 .to.throw(/Error unknown route type nope/);306 expect(log.count).to.equal(1);307 log.checkMocks();308 });309 describe('[github]', () => {310 it('checks the headers', () => {311 let route = {312 type: 'github'313 };314 let req = {315 headers: {}316 };317 log.mock((msg, status) => {318 expect(status).to.equal(2);319 expect(msg).to.match(/Error for route type github: Invalid headers/);320 });321 expect(() => whs._parseRequest(req, route))322 .to.throw(/Error for route type github: Invalid headers/);323 log.checkMocks();324 });325 it('doesn\'t throw if headers found', () => {326 let route = {};327 let req = {328 headers: {329 'x-github-event': 'push',330 'x-hub-signature': 'sha1=asdadsa'331 }332 };333 expect(() => whs._parseRequest(req, route)).to.not.throw();334 });335 it('checks if secret fails', () => {336 let route = {337 secret: 'lol'338 };339 let req = {340 headers: {341 'x-github-event': 'push',342 'x-hub-signature': 'sha1=nopenopenope'343 },344 rawBody: 'superbody'345 };346 log.mock((msg, status) => {347 expect(status).to.equal(2);348 expect(msg).to.match(/Error for route type github: Invalid secret/);349 });350 expect(() => whs._parseRequest(req, route))351 .to.throw(/Error for route type github: Invalid secret/);352 log.checkMocks();353 });354 it('checks if secret works', () => {355 let route = {356 secret: 'lol'357 };358 let req = {359 headers: {360 'x-github-event': 'push',361 'x-hub-signature': 'sha1=241946ca6d19a74a9e52ea4b6a59ceb9c5cf309f'362 },363 rawBody: '{"lol":"yeah"}'364 };365 expect(() => whs._parseRequest(req, route)).to.not.throw();366 });367 it('returns the action', () => {368 let route = {};369 let req = {370 headers: {371 'x-github-event': 'push',372 'x-hub-signature': 'sha1=241949ceb9c5cf309f'373 },374 body: '{"lol":"yeah"}'375 };376 let result = whs._parseRequest(req, route);377 expect(result.action).to.equal('push');378 });379 it('returns the repository name', () => {380 let route = {};381 let req = {382 headers: {383 'x-github-event': 'push',384 'x-hub-signature': 'sha1=241949ceb9c5cf309f'385 },386 body: JSON.stringify({387 repository: {388 name: 'pm2-hooks'389 }390 })391 };392 let result = whs._parseRequest(req, route);393 expect(result.name).to.equal('pm2-hooks');394 });395 it('returns the branch name', () => {396 let route = {};397 let req = {398 headers: {399 'x-github-event': 'push',400 'x-hub-signature': 'sha1=241949ceb9c5cf309f'401 },402 body: JSON.stringify({403 ref: 'refs/heads/develop',404 repository: {405 name: 'pm2-hooks'406 }407 })408 };409 let result = whs._parseRequest(req, route);410 expect(result.branch).to.equal('develop');411 });412 it('works with a payload key', () => {413 let route = {};414 let req = {415 headers: {416 'x-github-event': 'push',417 'x-hub-signature': 'sha1=241949ceb9c5cf309f'418 },419 body: {420 payload: JSON.stringify({421 ref: 'refs/heads/develop',422 repository: {423 name: 'pm2-hooks'424 }425 })426 }427 };428 let result = whs._parseRequest(req, route);429 expect(result.branch).to.equal('develop');430 });431 it('real example', () => {432 let mock = mocks.github.push;433 let route = {};434 let req = {435 headers: mock.headers,436 body: JSON.stringify(mock.body)437 };438 let result = whs._parseRequest(req, route);439 expect(result).to.deep.equal({440 action: 'push',441 branch: 'changes',442 name: 'public-repo'443 });444 });445 });446 describe('[bitbucket]', () => {447 it('checks the headers', () => {448 let route = {449 type: 'bitbucket'450 };451 let req = {452 headers: {}453 };454 log.mock((msg, status) => {455 expect(status).to.equal(2);456 expect(msg).to.match(/Error for route type bitbucket: Invalid headers/);457 });458 expect(() => whs._parseRequest(req, route))459 .to.throw(/Error for route type bitbucket: Invalid headers/);460 log.checkMocks();461 });462 it('throw if no body found', () => {463 let route = {};464 let req = {465 headers: mocks.bitbucket.push.headers,466 body: {}467 };468 log.mock((msg, status) => {469 expect(status).to.equal(2);470 expect(msg).to.match(/Error for route type bitbucket: Invalid body/);471 });472 expect(() => whs._parseRequest(req, route))473 .to.throw(/Error for route type bitbucket: Invalid body/);474 log.checkMocks();475 });476 it('throw if body isn\'t an object', () => {477 let route = {};478 let req = {479 headers: mocks.bitbucket.push.headers,480 body: 'nope'481 };482 log.mock((msg, status) => {483 expect(status).to.equal(2);484 expect(msg).to.match(/Error for route type bitbucket: Invalid body/);485 });486 expect(() => whs._parseRequest(req, route))487 .to.throw(/Error for route type bitbucket: Invalid body/);488 log.checkMocks();489 });490 it('throw if uncapable of find the action', () => {491 let route = {};492 let req = {493 headers: _.clone(mocks.bitbucket.push.headers),494 body: {}495 };496 req.headers['X-Event-Key'] = 'repo:';497 log.mock((msg, status) => {498 expect(status).to.equal(2);499 expect(msg).to.match(/Error for route type bitbucket: Invalid headers/);500 });501 expect(() => whs._parseRequest(req, route))502 .to.throw(/Error for route type bitbucket: Invalid headers/);503 log.checkMocks();504 });505 it('throw if invalid "changes" key found', () => {506 let route = {};507 let req = {508 headers: mocks.bitbucket.push.headers,509 body: {510 push: {}511 }512 };513 log.mock((msg, status) => {514 expect(status).to.equal(2);515 expect(msg).to.match(/Error for route type bitbucket: Invalid "changes" key on body/);516 });517 expect(() => whs._parseRequest(req, route))518 .to.throw(/Error for route type bitbucket: Invalid "changes" key on body/);519 log.checkMocks();520 });521 it('throws when there is a secret, as is not supported yet', () => {522 let route = {523 type: 'bitbucket',524 secret: 'lol'525 };526 let req = {527 headers: mocks.bitbucket.push.headers,528 body: {}529 };530 log.mock((msg, status) => {531 expect(status).to.equal(2);532 expect(msg).to.match(/Error for route type bitbucket: Secret not supported for bitbucket yet/);533 });534 expect(() => whs._parseRequest(req, route))535 .to.throw(/Error for route type bitbucket: Secret not supported for bitbucket yet/);536 log.checkMocks();537 });538 it('returns the action', () => {539 let route = {};540 let req = mocks.bitbucket.push;541 let result = whs._parseRequest(req, route);542 expect(result.action).to.equal('push');543 });544 it('returns the repository name', () => {545 let route = {};546 let req = mocks.bitbucket.push;547 let result = whs._parseRequest(req, route);548 expect(result.name).to.equal('pm2-hooks');549 });550 it('returns the branch name', () => {551 let route = {};552 let req = mocks.bitbucket.push;553 let result = whs._parseRequest(req, route);554 expect(result.branch).to.equal('master');555 });556 });557 });558 describe('_getRouteName', () => {559 let whs, mockReq;560 before(() => {561 whs = new WebhookServer({562 port: 1234,563 routes: {564 demo: {565 method() {}566 }567 }...

Full Screen

Full Screen

AttributeController.js

Source:AttributeController.js Github

copy

Full Screen

...36 * @param request37 * @param response38 */39 statistics(request, response) {40 var options = this._parseRequest(request.body);41 var uuid = new UUID().toString();42 logger.info(`AttributeController#statistics UUID: ${uuid} Start: ${moment().format()} Attributes: `, options.attributes);43 var distribution = request.body.distribution;44 let attributes = new Attributes(options.areaTemplate, options.periods, options.places, options.attributes);45 this._statistics.statistics(attributes, options.attributesMap, distribution).then(json => {46 response.json({attributes: json});47 logger.info(`AttributeController#statistics UUID: ${uuid} End: ${moment().format()}`);48 }).catch(err => {49 response.status(500).json({status: 'err', message: err});50 throw new Error(51 logger.error(`AttributeController#statistics Error: `, err)52 )53 })54 }55 filter(request, response) {56 var options = this._parseRequest(request.body);57 var uuid = new UUID().toString();58 logger.info(`AttributeController#filter UUID: ${uuid} Start: ${moment().format()}`);59 let attributes = new Attributes(options.areaTemplate, options.periods, options.places, options.attributes);60 this._filter.statistics(attributes, options.attributesMap, options.attributes).then(json => {61 let result = this._deduplicate(_.flatten(json), json.length);62 response.json(result);63 logger.info(`AttributeController#filter UUID: ${uuid} End: ${moment().format()}`);64 }).catch(err => {65 response.status(500).json({status: 'err', message: err});66 throw new Error(67 logger.error(`AttributeController#filter Error: `, err)68 )69 });70 }71 /**72 * It returns amount of areas which satisfy all limitations passed as the part of the result. There is always only one73 * number. If there is issue 500 is returned.74 * The sql here doesnt need geometry.75 * @param request76 * @param response77 */78 amount(request, response) {79 var options = this._parseRequest(request.body);80 var uuid = new UUID().toString();81 logger.info(`AttributeController#amount UUID: ${uuid} Start: ${moment().format()}`);82 // When I ask for multiple periods, it is the only time, where it actually needs the deduplication and stuff.83 // Otherwise it is actually quite simple.84 let attributes = new Attributes(options.areaTemplate, options.periods, options.places, options.attributes);85 if(options.periods.length > 1) {86 this._filter.statistics(attributes, options.attributesMap, options.attributes).then(json => {87 let result = this._deduplicate(_.flatten(json), json.length);88 response.json({amount: result.length});89 logger.info(`AttributeController#amount UUID: ${uuid} End: ${moment().format()}`);90 }).catch(err => {91 response.status(500).json({status: 'err', message: err});92 throw new Error(93 logger.error(`AttributeController#amount Error: `, err)94 )95 });96 } else {97 this._filter.amount(attributes, options.attributes).then(amount => {98 response.json({amount: amount});99 logger.info(`AttributeController#amount UUID: ${uuid} End: ${moment().format()}`);100 }).catch(err => {101 response.status(500).json({status: 'err', message: err});102 throw new Error(103 logger.error(`AttributeController#amount Error: `, err)104 )105 });106 }107 }108 /**109 * Returns values for received attributes for specific polygon.110 * @param request111 * @param response112 */113 info(request, response) {114 var options = this._parseRequest(request.body);115 let gid = request.body.gid;116 var uuid = new UUID().toString();117 logger.info(`AttributeController#info UUID: ${uuid} Start: ${moment().format()}`);118 let attributesObj = new AttributesForInfo(options.areaTemplate, options.periods, options.places, options.attributes);119 this._info.statistics(attributesObj, options.attributesMap, gid).then(json => {120 response.json(json);121 logger.info(`AttributeController#info UUID: ${uuid} End: ${moment().format()}`);122 }).catch(err => {123 response.status(500).json({status: 'err', message: err});124 throw new Error(125 logger.error(`AttributeController#info Error: `, err)126 )127 });128 }129 /**130 * Get bounding box for given areas131 * @param request132 * @param response133 */134 getBoundingBox(request,response){135 let areas = request.body.areas;136 let periods = request.body.periods;137 let promises = [];138 if (!areas){139 response.json({140 status: "error",141 message: "No selected area!"142 });143 }144 areas.map(locationObj => {145 let areaTemplate = locationObj.at;146 let options = this._parseRequestForBoundingBox(areaTemplate, locationObj.loc, periods);147 let attributesObj = new AttributesForInfo(options.areaTemplate, options.periods, options.places, options.attributes);148 promises.push(this._info.getBoundingBoxes(attributesObj, locationObj.gids));149 });150 let self = this;151 Promise.all(promises).then(function(result){152 let extents = [];153 if (result && result.length){154 result.map(areas => {155 areas.map(extent => {156 extents.push(extent);157 });158 });159 } else {160 response.json({161 status: "error",162 message: "No selected area!"163 });164 }165 return extents;166 }).catch(err => {167 response.status(500).json({status: 'err', message: err});168 throw new Error(169 logger.error(`AttributeController#getBoundingBox Error: `, err)170 )171 }).then(function(extents){172 if (extents.length){173 let points = [];174 extents.map(extent => {175 extent.map(coord => {176 points.push(coord);177 });178 });179 let bbox = self._info.boundingBox.getExtentFromPoints(points);180 response.json({181 status: "ok",182 bbox: bbox183 });184 }185 }).catch(err => {186 response.status(500).json({status: 'err', message: err});187 throw new Error(188 logger.error(`AttributeController#getBoundingBox Error: `, err)189 )190 });191 }192 _parseRequestForBoundingBox(areaTemplate, location, periods) {193 let attributes = [];194 let attributesMap = {};195 attributes.forEach(196 attribute => attributesMap[`as_${attribute.attributeSet}_attr_${attribute.attribute}`] = attribute197 );198 return {199 attributes: attributes,200 attributesMap: attributesMap,201 areaTemplate: Number(areaTemplate),202 periods: periods.map(period => Number(period)),203 places: [Number(location)]204 };205 }206 _parseRequest(params) {207 let attributes;208 if (!params.isArray){209 attributes = _.toArray(params.attributes);210 } else {211 attributes = params.attributes;212 }213 var attributesMap = {};214 attributes.forEach(215 attribute => attributesMap[`as_${attribute.attributeSet}_attr_${attribute.attribute}`] = attribute216 );217 return {218 attributes: attributes,219 attributesMap: attributesMap,220 areaTemplate: Number(params.areaTemplate),...

Full Screen

Full Screen

vlc.js

Source:vlc.js Github

copy

Full Screen

...42 {43 var time = 1000;44 if(!err && this._intervalEnabled)45 {46 this._parseRequest(result);47 var isPlaying = (result.state === 'playing');48 time = this._getProbeTime(isPlaying, result.time, result.rate);49 }50 if(this._intervalEnabled)51 this._getDataTimeout = setTimeout(() => onTimeout(), time);52 });53 },54 _parseRequest: function(result)55 {56 for(var key in playerData)57 {58 var value = result[playerData[key]];59 switch(key)60 {61 case 'pause':62 value = (value === 'paused');63 break;64 case 'eof-reached':65 value = (launched && !loading && value === 'stopped');66 break;67 case 'time-pos':68 case 'duration':69 value = parseInt(value);70 if(value < 0)71 continue;72 else if(!launched && key === 'time-pos' && value > 0)73 launched = true;74 break;75 case 'volume':76 value = Math.round(value / 2.56) / 100;77 if(value < 0)78 continue;79 break;80 case 'speed':81 value = Number(parseFloat(value).toFixed(2));82 if(previous.speed && previous.speed != value)83 this._onSpeedChanged(value);84 break;85 default:86 if(value == 'true')87 value = true;88 else if(value == 'false')89 value = false;90 break;91 }92 if(93 previous.hasOwnProperty(key)94 && previous[key] === value95 )96 continue;97 previous[key] = value;98 this.emit('playback', { name: key, value: value });99 }100 previous.repeat = (result.repeat === true || result.repeat === 'true');101 previous.fullscreen = (result.fullscreen > 0);102 if(result.currentplid > 0)103 previous.id = result.currentplid;104 if(105 !result.information106 || !result.information.category107 || !result.information.category.length108 || (streams.count109 && streams.count === result.information.category.length)110 )111 return;112 streams = {113 count: result.information.category.length,114 video: [],115 audio: [],116 subs: []117 };118 for(var cat of result.information.category)119 {120 if(!cat['$'].name.startsWith('Stream'))121 continue;122 var index = cat['$'].name.split(' ')[1];123 var streamType = cat.info.find(inf => inf['$'].name === 'Type');124 switch(streamType._)125 {126 case 'Video':127 streams.video.push(index);128 break;129 case 'Audio':130 streams.audio.push(index);131 break;132 case 'Subtitle':133 streams.subs.push(index);134 break;135 default:136 break;137 }138 }139 for(var type in streams)140 {141 if(type === 'count')142 continue;143 if(streams[type].length > 1)144 streams[type].sort();145 }146 this.emit('streams-changed');147 },148 cleanup: function()149 {150 this._intervalEnabled = false;151 if(this._getDataTimeout)152 clearTimeout(this._getDataTimeout);153 },154 _getSpawnArgs: function(opts)155 {156 /* VLC requires password for web interface */157 httpOpts.pass = opts.httpPass || 'vlc';158 httpOpts.port = opts.httpPort;159 var presetArgs = [160 '--no-play-and-exit',161 '--no-qt-recentplay',162 '--qt-continue', '0',163 '--image-duration', '-1',164 '--extraintf', 'http',165 '--http-port', httpOpts.port,166 '--http-password', httpOpts.pass,167 opts.media168 ];169 return [ ...opts.args, ...presetArgs ];170 },171 command: function(params, cb)172 {173 cb = cb || noop;174 var command = null;175 if(!Array.isArray(params))176 return cb(new Error('No command parameters array!'));177 for(var cmd of params)178 {179 if(!command)180 command = cmd;181 else182 command += `&${cmd}`;183 }184 httpOpts.path = '/requests/status.xml?command=' + command;185 helper.httpRequest(httpOpts, (err, result) =>186 {187 if(err) return cb(err);188 httpOpts.path = '/requests/status.xml';189 helper.httpRequest(httpOpts, (err, result) =>190 {191 if(err) return cb(err);192 this._debug(command);193 this._parseRequest(result);194 cb(null);195 });196 });197 },198 play: function(cb)199 {200 cb = cb || noop;201 if(previous.pause)202 this.cyclePause(cb);203 else204 cb(null);205 },206 pause: function(cb)207 {208 cb = cb || noop;209 if(!previous.pause)210 this.cyclePause(cb);211 else212 cb(null);213 },214 cyclePause: function(cb)215 {216 cb = cb || noop;217 this.command(['pl_pause'], cb);218 },219 _load: function(media, cb)220 {221 cb = cb || noop;222 previous.duration = null;223 loading = true;224 var changeTimeout;225 const onStreamsChange = function()226 {227 if(changeTimeout)228 {229 clearTimeout(changeTimeout);230 changeTimeout = null;231 }232 loading = false;233 cb(null);234 }235 var delId = previous.id;236 this.command(['in_play', `input=${media}`], (err) =>237 {238 if(err) return cb(err);239 currStreams = {};240 this.command(['pl_delete', `id=${delId}`], (err) =>241 {242 if(err) return cb(err);243 changeTimeout = setTimeout(() =>244 {245 changeTimeout = null;246 loading = false;247 this.removeListener('streams-changed', onStreamsChange);248 cb(new Error('Streams change timeout'));249 }, 15000);250 this.once('streams-changed', onStreamsChange);251 streams = {};252 httpOpts.path = '/requests/status.xml';253 helper.httpRequest(httpOpts, (err, result) =>254 {255 /* Ignore this req and wait for next */256 if(err) return;257 this._parseRequest(result);258 });259 });260 });261 },262 seek: function(position, cb)263 {264 cb = cb || noop;265 position = (position > 0) ? parseInt(position) : 0;266 this.command(['seek', `val=${position}`], cb);267 },268 setVolume: function(value, cb)269 {270 cb = cb || noop;271 value = (value > 0) ? parseInt(value * 256) : 0;272 this.command(['volume', `val=${value}`], (err) =>273 {274 if(err) return cb(err);275 /* Setting volume on VLC sometimes requires another refresh */276 httpOpts.path = '/requests/status.xml';277 helper.httpRequest(httpOpts, (err, result) =>278 {279 if(err) return cb(err);280 this._parseRequest(result);281 cb(null);282 });283 });284 },285 setSpeed: function(value, cb)286 {287 cb = cb || noop;288 value = (value > 0) ? value : 1;289 this.command(['rate', `val=${value}`], cb);290 },291 setRepeat: function(isEnabled, cb)292 {293 cb = cb || noop;294 switch(isEnabled)...

Full Screen

Full Screen

WebhookManager.js

Source:WebhookManager.js Github

copy

Full Screen

...22 this.bot.emit("warn", `${port} is already being listened on`);23 }24 } else {25 const server = http.createServer((req, res) => {26 this._parseRequest(port, req, res);27 }).listen(port, () => {28 if (this.bot.Logger) {29 this.bot.Logger.info(`Listening on http://0.0.0.0:${port}`);30 } else {31 console.log(`Listening on http://0.0.0.0:${port}`);32 }33 });34 this.ports.set(port, { server: server, waitFor: [] });35 }36 }37 /**38 * Waits for the specified URL on the port39 * @param {Number} port Port assiociated with the function40 * @param {String} waitFor URL to wait for (i.e. /bfdwebhook)41 * @param {Function} fn Function to be executed upon request (bot, data)42 * @param {String} [auth] Authoirsation token to compare43 */44 waitFor(port, waitFor, fn, auth = undefined) {45 if (!this.ports.has(port)) {46 if (this.bot.Logger) {47 this.bot.Logger.warn(`${port} hasn't been registered yet`);48 } else {49 this.bot.emit("warn", `${port} hasn't been registered yet`);50 }51 } else {52 if ((typeof waitFor !== "string" || !waitFor.startsWith("/"))53 && typeof fn !== "function"54 && !["string", "undefined"].includes(auth)) {55 if (this.bot.Logger) {56 this.bot.Logger.warn(`Can't wait on ${port}${waitFor}, invalid information was provided`);57 } else {58 this.bot.emit("warn", `Can't wait on ${port}${waitFor}, invalid information was provided`);59 }60 }61 const portInfo = this.ports.get(port);62 portInfo.waitFor.push({ url: waitFor, fn: fn, auth: auth });63 this.ports.set(port, portInfo);64 }65 }66 /**67 * Manages incomming requests68 * @param {Number} port 69 * @param {http.IncomingMessage} req 70 * @param {http.ServerResponse} res 71 */72 _parseRequest(port, req, res) {73 if (!this.ports.has(port)) {74 return;75 }76 const url = req.url;77 const waitFors = this.ports.get(port).waitFor;78 for (const waitFor of waitFors) {79 if (waitFor.url === url && req.method === "POST") {80 if (waitFor.auth != undefined) {81 if (req.headers.authorization !== waitFor.auth) {82 return;83 }84 }85 if (req.headers["content-type"] === "application/json") {86 let data = "";...

Full Screen

Full Screen

index.spec.js

Source:index.spec.js Github

copy

Full Screen

...15 })16 })17 describe('_parseRequest', () => {18 it('Should be able to parse query parameters properly', () => {19 expect(obj._parseRequest('http://test.com/whatever.html?test=hi&what=ever')).to.deep.equal({20 test: 'hi',21 what: 'ever'22 })23 })24 })25 describe('stub and unstub', () => {26 it('Should allow unstubbing', () => {27 expect(obj._stubbed).to.be.false28 obj.stub()29 expect(obj._stubbed).to.be.true30 obj.unstub()31 expect(obj._stubbed).to.be.false32 })33 })...

Full Screen

Full Screen

request.js

Source:request.js Github

copy

Full Screen

1import {parseRequest} from './utils';2export default class HTTPRequest {3 constructor(rawReq) {4 if (rawReq) {5 const packet = this._parseRequest(rawReq);6 this.method = packet.method;7 this.path = packet.path;8 this.httpVersion = packet.httpVersion;9 this.headers = packet.headers;10 this.payload = packet.payload;11 } else {12 this.method = 'GET';13 this.path = '/';14 this.httpVersion = 'HTTP/1.1';15 this.headers = {};16 this.payload = '';17 }18 }19 _parseRequest(rawReq) {20 const {firstLineParts, ...request} = parseRequest(rawReq);21 request.method = firstLineParts[0];22 request.path = firstLineParts[1];23 request.httpVersion = firstLineParts[2];24 return request;25 }26 toString() {27 let result = '';28 result += `${this.method} ${this.path} ${this.httpVersion}\r\n`;29 for (const header in this.headers) {30 result += `${header}: ${this.headers[header]}\r\n`;31 }32 result += '\r\n';33 result += this.payload;...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1export default class RequestError {2 constructor(request, originalError ) {3 this.uri = `${ request.method.toUpperCase() } ${ request.path }`;4 this.isError = true;5 this._parseRequest(request);6 if (originalError) {7 const { message, stack, constructor } = originalError;8 this.sourceError = { message, stack, name: constructor.name };9 }10 }11 toJSON() {12 const { uri, sourceError, message, name } = this;13 return {14 name,15 message,16 uri,17 sourceError: {18 name: sourceError && sourceError.name || 'Unknown',19 message: sourceError && sourceError.message || 'Unknown'20 }21 };22 }23 _parseRequest(req) {24 const { id, headers, info, method, params, path, payload, query } = req;25 this.request = {26 id,27 headers,28 method: method.toUpperCase(),29 path,30 params,31 query,32 payload,33 issuer: info.remoteAddress34 };35 }...

Full Screen

Full Screen

01b7020c8fa6b5ae2807ed257eee948703094171controller.spec.js

Source:01b7020c8fa6b5ae2807ed257eee948703094171controller.spec.js Github

copy

Full Screen

1var Controller = require( "./controller" );2describe( "Controller", function() {3 it( "_parseRequest parse JSON", function() {4 var controller = new Controller();5 expect( controller._parseRequest( '{ "command" : "notifications", "data" : "" }' ) ).toEqual({6 command : 'notifications',7 data : ''8 });9 });10 it( "_parseRequest wrong JSON return Error", function() {11 var controller = new Controller();12 expect( function() {13 controller._parseRequest( '{ "command" : }' );14 } ).toThrow();15 }); 16 it( "_parseRequest fields 'command' and 'data' are required", function() {17 var controller = new Controller();18 expect( function() {19 controller._parseRequest( '{ "command" : "notifications" }' );20 } ).toThrow();21 expect( function() {22 controller._parseRequest( '{ "data" : "" }' );23 } ).toThrow();24 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _parseRequest } = require('playwright/lib/utils/utils');2const request = {3 headers: {4 },5 postData: '{"name": "John"}',6};7const parsedRequest = _parseRequest(request);8console.log(parsedRequest);9{10 headers: {11 },12 postData: '{"name": "John"}'13}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _parseRequest } = require('playwright/lib/server/network');2const request = _parseRequest({3 headers: {4 },5});6console.log(request.postDataBuffer());

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _parseRequest } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');2const { parse } = require('playwright/lib/utils/parseRequest.js');3const request = {4};5const parsedRequest = _parseRequest(request);6console.log(parsedRequest);7const parsedRequest2 = parse(request);8console.log(parsedRequest2);9const { _parseRequest } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');10const { parse } = require('playwright/lib/utils/parseRequest.js');11const request = {12};13const parsedRequest = _parseRequest(request);14console.log(parsedRequest);15const parsedRequest2 = parse(request);16console.log(parsedRequest2);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Playwright } = require('playwright');2const { Internal } = require('playwright/lib/server/playwright.js');3const playwright = new Playwright();4const internal = new Internal(playwright);5const request = {6 headers: {7 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',8 },9};10const result = internal._parseRequest(request);11console.log(result);12const { Playwright } = require('playwright');13const { Internal } = require('playwright/lib/server/playwright.js');14const playwright = new Playwright();15const internal = new Internal(playwright);16const request = {17 headers: {18 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',19 },20};21const result = internal._parseRequest(request);22console.log(result);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { parseRequest } = require('playwright/lib/server/network.js');2const { parseRequest } = require('playwright/lib/server/network.js');3const request = parseRequest({4 headers: { 'content-type': 'application/json' },5 postData: '{"foo":"bar"}'6});7console.log(request.postDataJSON());8const { parseRequest } = require('playwright/lib/server/network.js');9const request = parseRequest({10 headers: { 'content-type': 'application/json' },11 postData: '{"foo":"bar"}'12});13console.log(request.postDataJSON());14const { parseRequest } = require('playwright/lib/server/network.js');15const request = parseRequest({16 headers: { 'content-type': 'application/json' },17 postData: '{"foo":"bar"}'18});19console.log(request.postDataJSON());20const { parseRequest } = require('playwright/lib/server/network.js');21const request = parseRequest({22 headers: { 'content-type': 'application/json' },23 postData: '{"foo":"bar"}'24});25console.log(request.postDataJSON());26const { parseRequest } = require('playwright/lib/server/network.js');27const request = parseRequest({28 headers: { 'content-type': 'application/json' },29 postData: '{"foo":"bar"}'30});31console.log(request.postDataJSON());32const { parseRequest } = require('playwright/lib/server/network.js');33const request = parseRequest({34 headers: { 'content-type': 'application/json' },35 postData: '{"foo":"bar"}'36});37console.log(request.postDataJSON());38const { parseRequest } = require('playwright/lib/server/network.js');39const request = parseRequest({

Full Screen

Using AI Code Generation

copy

Full Screen

1const { _parseRequest } = require('playwright/lib/server/network');2const { parse } = require('url');3const request = {4 headers: {},5};6const parsed = _parseRequest(request, parse(url));7console.log(parsed);8{9 headers: {},10}11const { _parseRequest } = require('playwright/lib/server/network');12const { parse } = require('url');13const request = {14 headers: {},15};16const parsed = _parseRequest(request, parse(url));17console.log(parsed);18{19 headers: {},20}21const { _parseRequest } = require('playwright/lib/server/network');22const { parse } = require('url');23const request = {24 headers: {},25};

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Playwright } = require('playwright');2const playwright = new Playwright();3const browserServer = playwright.chromium.launchServer();4(async () => {5 const { port } = await browserServer.start();6 const wsEndpoint = await browserServer.wsEndpoint();7 console.log(wsEndpoint);8 const { headers, method, postData, path } = playwright._parseRequest(wsEndpoint);9 console.log(headers);10 console.log(method);11 console.log(postData);12 console.log(path);13 await browserServer.close();14})();

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful