How to use _parseRequest method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

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

01b7020c8fa6b5ae2807ed257eee948703094171controller.spec.js

Source: 01b7020c8fa6b5ae2807ed257eee948703094171controller.spec.js Github

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

WebhookServer.js

Source: WebhookServer.js Github

copy
1/**
2 * Created by desaroger on 23/02/17.
3 */
4/* eslint-disable global-require */
5
6let _ = require('lodash');
7let sinon = require('sinon');
8let { expect, c, callApi, log } = require('./assets');
9let WebhookServer = require('../src/WebhookServer');
10
11let mocks = getMocks();
12
13describe('webhookServer', () => {
14    beforeEach(() => {
15        log.restore();
16    });
17
18    it('is a function', () => {
19        expect(WebhookServer).to.be.a('function');
20    });
21
22    it('can be instantiated', () => {
23        expect(() => new WebhookServer()).to.not.throw();
24    });
25
26    describe('the instance', (whs, calls = 0) => {
27        before(() => {
28            whs = new WebhookServer({
29                port: 1234,
30                routes: {
31                    demo: {
32                        type: 'github',
33                        method() {
34                            calls++;
35                        }
36                    }
37                }
38            });
39        });
40        afterEach(() => whs.stop());
41
42        it('not has the server created', () => {
43            expect(whs.server).to.not.be.ok;
44        });
45
46        it('has the expected methods', () => {
47            expect(whs.isRunning).to.be.a('function');
48            expect(whs.start).to.be.a('function');
49            expect(whs.stop).to.be.a('function');
50        });
51
52        it('is not running initially', () => {
53            expect(whs.isRunning()).to.equal(false);
54        });
55
56        it('can be started', () => {
57            return expect(whs.start()).to.eventually.be.fulfilled;
58        });
59
60        it('shows as running', () => {
61            return whs.stop()
62                .then(() => whs.start())
63                .then(() => {
64                    expect(whs.isRunning()).to.equal(true);
65                });
66        });
67    });
68
69    describe('call handler', (whs, calls = 0, method) => {
70        before(() => {
71            whs = new WebhookServer({
72                port: 1234,
73                routes: {
74                    working: {
75                        method() { calls++; }
76                    },
77                    withoutType: {
78                        method() { calls++; }
79                    },
80                    throwsError: {
81                        method() {
82                            throw new Error('Test error');
83                        }
84                    },
85                    throwsString: {
86                        method() {
87                            throw 'Test throw string'; // eslint-disable-line no-throw-literal
88                        }
89                    },
90                    checkPayload: {
91                        type: 'test',
92                        method(...args) {
93                            return method.call(this, ...args);
94                        }
95                    }
96                }
97            });
98        });
99        afterEach(() => {
100            calls = 0;
101            return whs.stop();
102        });
103
104        it('the server is actually listening', c(function* () {
105            let spy = sinon.spy(whs, '_handleCall');
106            yield whs.start();
107            log.restore();
108
109            // Logs
110            log.mock((msg, status) => {
111                expect(msg).to.match(/no route found on url/i);
112                expect(status).to.equal(1);
113            });
114            yield callApi();
115            log.mock((msg, status) => {
116                expect(msg).to.match(/route "asd" not found/i);
117                expect(status).to.equal(1);
118            });
119            yield callApi('/asd');
120
121            expect(spy.calledTwice).to.equal(true);
122            spy.restore();
123            expect(log.count).to.equal(2);
124            log.checkMocks();
125        }));
126
127        it('returns success if the route works', c(function* () {
128            expect(calls).to.equal(0);
129            yield whs.start();
130            log.mock((msg, status) => {
131                expect(msg).to.match(/route "working" was found/i);
132                expect(status).to.equal(0);
133            });
134            let body = yield callApi('/working');
135            expect(body).to.be.deep.equal({
136                $statusCode: 200,
137                status: 'success',
138                message: 'Route "working" was found',
139                code: 0
140            });
141            expect(calls).to.equal(1);
142            expect(log.count).to.equal(1);
143            log.checkMocks();
144        }));
145
146        it('works even though there is no type', c(function* () {
147            expect(calls).to.equal(0);
148            yield whs.start();
149            log.mock((msg, status) => {
150                expect(msg).to.match(/route "withoutType" was found/i);
151                expect(status).to.equal(0);
152            });
153            let body = yield callApi('/withoutType');
154            expect(body).to.be.deep.equal({
155                $statusCode: 200,
156                status: 'success',
157                message: 'Route "withoutType" was found',
158                code: 0
159            });
160            expect(calls).to.equal(1);
161            expect(log.count).to.equal(1);
162            log.checkMocks();
163        }));
164
165        it('returns a warning if called a non-existent route', c(function* () {
166            expect(calls).to.equal(0);
167            yield whs.start();
168            log.mock((msg, status) => {
169                expect(msg).to.match(/route "lol" not found/i);
170                expect(status).to.equal(1);
171            });
172            let body = yield callApi('/lol');
173            expect(body).to.be.deep.equal({
174                $statusCode: 400,
175                status: 'warning',
176                message: 'Route "lol" not found',
177                code: 1
178            });
179            expect(calls).to.equal(0);
180            log.checkMocks();
181        }));
182
183        it('returns an error if the method triggers an error', c(function* () {
184            expect(calls).to.equal(0);
185            yield whs.start();
186            log.mock((msg, status) => {
187                expect(msg).to.match(/route "throwsError" method error: Test error/i);
188                expect(status).to.equal(2);
189            });
190            let body = yield callApi('/throwsError');
191            expect(body).to.be.deep.equal({
192                $statusCode: 500,
193                status: 'error',
194                message: 'Route "throwsError" method error: Test error',
195                code: 2
196            });
197            expect(calls).to.equal(0);
198            log.checkMocks();
199        }));
200
201        it('returns an error if the method triggers a value', c(function* () {
202            expect(calls).to.equal(0);
203            yield whs.start();
204            log.mock((msg, status) => {
205                expect(msg).to.match(/route "throwsString" method error: Test throw string/i);
206                expect(status).to.equal(2);
207            });
208            let body = yield callApi('/throwsString');
209            expect(body).to.be.deep.equal({
210                $statusCode: 500,
211                status: 'error',
212                message: 'Route "throwsString" method error: Test throw string',
213                code: 2
214            });
215            expect(calls).to.equal(0);
216            log.checkMocks();
217        }));
218
219        it('pass the payload to the method', c(function* () {
220            expect(calls).to.equal(0);
221            yield whs.start();
222            method = (payload) => {
223                expect(payload).to.deep.equal({
224                    name: 'pm2-hooks',
225                    action: 'push',
226                    branch: 'master'
227                });
228            };
229            log.mock((msg, status) => {
230                expect(msg).to.match(/route "checkPayload" was found/i);
231                expect(status).to.equal(0);
232            });
233            let body = yield callApi(
234                '/checkPayload',
235                {
236                    name: 'pm2-hooks',
237                    action: 'push',
238                    branch: 'master'
239                }
240            );
241            expect(body).to.be.deep.equal({
242                $statusCode: 200,
243                status: 'success',
244                message: 'Route "checkPayload" was found',
245                code: 0
246            });
247            expect(calls).to.equal(0);
248            log.checkMocks();
249        }));
250
251        it('handles unexpected errors', c(function* () {
252            expect(calls).to.equal(0);
253            yield whs.start();
254
255            log.mock((msg, status) => {
256                throw new Error('SuperError');
257            }, { checkNow: true });
258            log.mock((msg, status) => {
259                expect(status).to.equal(2);
260                expect(msg).to.match(/SuperError/);
261            });
262            let body = yield callApi(
263                '/working',
264                {
265                    name: 'pm2-hooks',
266                    action: 'push',
267                    branch: 'master'
268                }
269            );
270            expect(body).to.be.deep.equal({
271                $statusCode: 500,
272                status: 'error',
273                message: 'Unexpected error: SuperError',
274                code: 2
275            });
276            expect(calls).to.equal(1);
277            log.checkMocks();
278        }));
279
280        it('throws an error if server previously listening', c(function* () {
281            yield expect(whs.start()).to.be.fulfilled;
282            yield expect(whs.start()).to.be.rejectedWith('Server previously started');
283        }));
284    });
285
286    describe('_parseRequest', () => {
287        let whs;
288        before(() => {
289            whs = new WebhookServer({
290                port: 1234,
291                routes: {
292                    demo: {
293                        method() {}
294                    }
295                }
296            });
297            sinon.spy(whs.options.routes.demo, 'method');
298        });
299
300        it('exists', () => {
301            expect(whs._parseRequest).to.be.a('function');
302        });
303
304        it('logs on error', () => {
305            let route = {
306                type: 'github'
307            };
308            let req = {
309                headers: {}
310            };
311            log.mock((msg, status) => {
312                expect(msg).to.match(/Error for route type github: Invalid headers/i);
313                expect(status).to.equal(2);
314            });
315            expect(() => whs._parseRequest(req, route))
316                .to.throw(/Error for route type github: Invalid headers/);
317            expect(log.count).to.equal(1);
318            log.checkMocks();
319        });
320
321        it('throws if unknown type', () => {
322            let route = {
323                type: 'nope'
324            };
325            let req = {
326                headers: {}
327            };
328            log.mock((msg, status) => {
329                expect(msg).to.match(/Error unknown route type nope/i);
330                expect(status).to.equal(2);
331            });
332            expect(() => whs._parseRequest(req, route))
333                .to.throw(/Error unknown route type nope/);
334            expect(log.count).to.equal(1);
335            log.checkMocks();
336        });
337
338        describe('[github]', () => {
339            it('checks the headers', () => {
340                let route = {
341                    type: 'github'
342                };
343                let req = {
344                    headers: {}
345                };
346                log.mock((msg, status) => {
347                    expect(status).to.equal(2);
348                    expect(msg).to.match(/Error for route type github: Invalid headers/);
349                });
350                expect(() => whs._parseRequest(req, route))
351                    .to.throw(/Error for route type github: Invalid headers/);
352                log.checkMocks();
353            });
354
355            it('doesn\'t throw if headers found', () => {
356                let route = {};
357                let req = {
358                    headers: {
359                        'x-github-event': 'push',
360                        'x-hub-signature': 'sha1=asdadsa'
361                    }
362                };
363                expect(() => whs._parseRequest(req, route)).to.not.throw();
364            });
365
366            it('checks if secret fails', () => {
367                let route = {
368                    secret: 'lol'
369                };
370                let req = {
371                    headers: {
372                        'x-github-event': 'push',
373                        'x-hub-signature': 'sha1=nopenopenope'
374                    },
375                    rawBody: 'superbody'
376                };
377                log.mock((msg, status) => {
378                    expect(status).to.equal(2);
379                    expect(msg).to.match(/Error for route type github: Invalid secret/);
380                });
381                expect(() => whs._parseRequest(req, route))
382                    .to.throw(/Error for route type github: Invalid secret/);
383                log.checkMocks();
384            });
385
386            it('checks if secret works', () => {
387                let route = {
388                    secret: 'lol'
389                };
390                let req = {
391                    headers: {
392                        'x-github-event': 'push',
393                        'x-hub-signature': 'sha1=241946ca6d19a74a9e52ea4b6a59ceb9c5cf309f'
394                    },
395                    rawBody: '{"lol":"yeah"}'
396                };
397                expect(() => whs._parseRequest(req, route)).to.not.throw();
398            });
399
400            it('returns the action', () => {
401                let route = {};
402                let req = {
403                    headers: {
404                        'x-github-event': 'push',
405                        'x-hub-signature': 'sha1=241949ceb9c5cf309f'
406                    },
407                    body: '{"lol":"yeah"}'
408                };
409                let result = whs._parseRequest(req, route);
410                expect(result.action).to.equal('push');
411            });
412
413            it('returns the repository name', () => {
414                let route = {};
415                let req = {
416                    headers: {
417                        'x-github-event': 'push',
418                        'x-hub-signature': 'sha1=241949ceb9c5cf309f'
419                    },
420                    body: JSON.stringify({
421                        repository: {
422                            name: 'pm2-hooks'
423                        }
424                    })
425                };
426                let result = whs._parseRequest(req, route);
427                expect(result.name).to.equal('pm2-hooks');
428            });
429
430            it('returns the branch name', () => {
431                let route = {};
432                let req = {
433                    headers: {
434                        'x-github-event': 'push',
435                        'x-hub-signature': 'sha1=241949ceb9c5cf309f'
436                    },
437                    body: JSON.stringify({
438                        ref: 'refs/heads/develop',
439                        repository: {
440                            name: 'pm2-hooks'
441                        }
442                    })
443                };
444                let result = whs._parseRequest(req, route);
445                expect(result.branch).to.equal('develop');
446            });
447
448            it('works with a payload key', () => {
449                let route = {};
450                let req = {
451                    headers: {
452                        'x-github-event': 'push',
453                        'x-hub-signature': 'sha1=241949ceb9c5cf309f'
454                    },
455                    body: {
456                        payload: JSON.stringify({
457                            ref: 'refs/heads/develop',
458                            repository: {
459                                name: 'pm2-hooks'
460                            }
461                        })
462                    }
463                };
464                let result = whs._parseRequest(req, route);
465                expect(result.branch).to.equal('develop');
466            });
467
468            it('real example', () => {
469                let mock = mocks.github.push;
470                let route = {};
471                let req = {
472                    headers: mock.headers,
473                    body: JSON.stringify(mock.body)
474                };
475                let result = whs._parseRequest(req, route);
476                expect(result).to.deep.equal({
477                    action: 'push',
478                    branch: 'changes',
479                    name: 'public-repo'
480                });
481            });
482        });
483
484        describe('[bitbucket]', () => {
485            it('checks the headers', () => {
486                let route = {
487                    type: 'bitbucket'
488                };
489                let req = {
490                    headers: {}
491                };
492                log.mock((msg, status) => {
493                    expect(status).to.equal(2);
494                    expect(msg).to.match(/Error for route type bitbucket: Invalid headers/);
495                });
496                expect(() => whs._parseRequest(req, route))
497                    .to.throw(/Error for route type bitbucket: Invalid headers/);
498                log.checkMocks();
499            });
500
501            it('throw if no body found', () => {
502                let route = {};
503                let req = {
504                    headers: mocks.bitbucket.push.headers,
505                    body: {}
506                };
507                log.mock((msg, status) => {
508                    expect(status).to.equal(2);
509                    expect(msg).to.match(/Error for route type bitbucket: Invalid body/);
510                });
511                expect(() => whs._parseRequest(req, route))
512                    .to.throw(/Error for route type bitbucket: Invalid body/);
513                log.checkMocks();
514            });
515
516            it('throw if body isn\'t an object', () => {
517                let route = {};
518                let req = {
519                    headers: mocks.bitbucket.push.headers,
520                    body: 'nope'
521                };
522                log.mock((msg, status) => {
523                    expect(status).to.equal(2);
524                    expect(msg).to.match(/Error for route type bitbucket: Invalid body/);
525                });
526                expect(() => whs._parseRequest(req, route))
527                    .to.throw(/Error for route type bitbucket: Invalid body/);
528                log.checkMocks();
529            });
530
531            it('throw if uncapable of find the action', () => {
532                let route = {};
533                let req = {
534                    headers: _.clone(mocks.bitbucket.push.headers),
535                    body: {}
536                };
537                req.headers['X-Event-Key'] = 'repo:';
538                log.mock((msg, status) => {
539                    expect(status).to.equal(2);
540                    expect(msg).to.match(/Error for route type bitbucket: Invalid headers/);
541                });
542                expect(() => whs._parseRequest(req, route))
543                    .to.throw(/Error for route type bitbucket: Invalid headers/);
544                log.checkMocks();
545            });
546
547            it('throw if invalid "changes" key found', () => {
548                let route = {};
549                let req = {
550                    headers: mocks.bitbucket.push.headers,
551                    body: {
552                        push: {}
553                    }
554                };
555                log.mock((msg, status) => {
556                    expect(status).to.equal(2);
557                    expect(msg).to.match(/Error for route type bitbucket: Invalid "changes" key on body/);
558                });
559                expect(() => whs._parseRequest(req, route))
560                    .to.throw(/Error for route type bitbucket: Invalid "changes" key on body/);
561                log.checkMocks();
562            });
563
564            it('throws when there is a secret, as is not supported yet', () => {
565                let route = {
566                    type: 'bitbucket',
567                    secret: 'lol'
568                };
569                let req = {
570                    headers: mocks.bitbucket.push.headers,
571                    body: {}
572                };
573                log.mock((msg, status) => {
574                    expect(status).to.equal(2);
575                    expect(msg).to.match(/Error for route type bitbucket: Secret not supported for bitbucket yet/);
576                });
577                expect(() => whs._parseRequest(req, route))
578                    .to.throw(/Error for route type bitbucket: Secret not supported for bitbucket yet/);
579                log.checkMocks();
580            });
581
582            it('returns the action', () => {
583                let route = {};
584                let req = mocks.bitbucket.push;
585                let result = whs._parseRequest(req, route);
586                expect(result.action).to.equal('push');
587            });
588
589            it('returns the repository name', () => {
590                let route = {};
591                let req = mocks.bitbucket.push;
592                let result = whs._parseRequest(req, route);
593                expect(result.name).to.equal('pm2-hooks');
594            });
595
596            it('returns the branch name', () => {
597                let route = {};
598                let req = mocks.bitbucket.push;
599                let result = whs._parseRequest(req, route);
600                expect(result.branch).to.equal('master');
601            });
602        });
603    });
604
605    describe('_getRouteName', () => {
606        let whs, mockReq;
607        before(() => {
608            whs = new WebhookServer({
609                port: 1234,
610                routes: {
611                    demo: {
612                        method() {}
613                    }
614                }
615            });
616            sinon.spy(whs.options.routes.demo, 'method');
617            mockReq = (url) => {
618                return {
619                    url
620                };
621            };
622        });
623
624        it('returns null if there is no url', () => {
625            let req = mockReq('');
626            expect(whs._getRouteName(req)).to.equal(null);
627            req = mockReq('/');
628            expect(whs._getRouteName(req)).to.equal(null);
629            req = mockReq(' // ');
630            expect(whs._getRouteName(req)).to.equal(null);
631        });
632
633        it('returns name despite it don\'t match', () => {
634            let req = mockReq('/nope');
635            expect(whs._getRouteName(req)).to.equal('nope');
636            req = mockReq('/nope/nope');
637            expect(whs._getRouteName(req)).to.equal('nope');
638        });
639
640        it('returns the match if matched', () => {
641            let req = mockReq('/demo');
642            expect(whs._getRouteName(req)).to.equal('demo');
643            req = mockReq('/demo?asd=2');
644            expect(whs._getRouteName(req)).to.equal('demo');
645        });
646    });
647});
648
649function getMocks() {
650    return {
651        bitbucket: {
652            push: require('./mocks/bitbucket_push.json')
653        },
654        github: {
655            push: require('./mocks/github_push.json')
656        }
657    };
658}
659
Full Screen

index.js

Source: index.js Github

copy
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
12  toJSON() {
13    const { uri, sourceError, message, name } = this;
14    return {
15      name,
16      message,
17      uri,
18      sourceError: {
19        name: sourceError && sourceError.name || 'Unknown',
20        message: sourceError && sourceError.message || 'Unknown'
21      }
22    };
23  }
24
25  _parseRequest(req) {
26    const { id, headers, info, method, params, path, payload, query } = req;
27    this.request = {
28      id,
29      headers,
30      method: method.toUpperCase(),
31      path,
32      params,
33      query,
34      payload,
35      issuer: info.remoteAddress
36    };
37  }
38}
39
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)