forked from puppeteer/puppeteer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
network.spec.ts
809 lines (718 loc) · 28.7 KB
/
network.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fs from 'fs';
import path from 'path';
import utils from './utils.js';
import expect from 'expect';
import {
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
itFailsFirefox,
describeFailsFirefox,
itChromeOnly,
itFirefoxOnly,
} from './mocha-utils'; // eslint-disable-line import/extensions
import { HTTPResponse } from '../lib/cjs/puppeteer/api-docs-entry.js';
describe('network', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.Events.Request', function () {
it('should fire for navigation requests', async () => {
const { page, server } = getTestState();
const requests = [];
page.on(
'request',
(request) => !utils.isFavicon(request) && requests.push(request)
);
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
});
it('should fire for iframes', async () => {
const { page, server } = getTestState();
const requests = [];
page.on(
'request',
(request) => !utils.isFavicon(request) && requests.push(request)
);
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(requests.length).toBe(2);
});
it('should fire for fetches', async () => {
const { page, server } = getTestState();
const requests = [];
page.on(
'request',
(request) => !utils.isFavicon(request) && requests.push(request)
);
await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => fetch('/empty.html'));
expect(requests.length).toBe(2);
});
});
describe('Request.frame', function () {
it('should work for main frame navigation request', async () => {
const { page, server } = getTestState();
const requests = [];
page.on(
'request',
(request) => !utils.isFavicon(request) && requests.push(request)
);
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests[0].frame()).toBe(page.mainFrame());
});
itFailsFirefox('should work for subframe navigation request', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
const requests = [];
page.on(
'request',
(request) => !utils.isFavicon(request) && requests.push(request)
);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests[0].frame()).toBe(page.frames()[1]);
});
it('should work for fetch requests', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
let requests = [];
page.on(
'request',
(request) => !utils.isFavicon(request) && requests.push(request)
);
await page.evaluate(() => fetch('/digits/1.png'));
requests = requests.filter(
(request) => !request.url().includes('favicon')
);
expect(requests.length).toBe(1);
expect(requests[0].frame()).toBe(page.mainFrame());
});
});
describe('Request.headers', function () {
itChromeOnly('should define Chrome as user agent header', async () => {
const { page, server } = getTestState();
const response = await page.goto(server.EMPTY_PAGE);
expect(response.request().headers()['user-agent']).toContain('Chrome');
});
itFirefoxOnly('should define Firefox as user agent header', async () => {
const { page, server } = getTestState();
const response = await page.goto(server.EMPTY_PAGE);
expect(response.request().headers()['user-agent']).toContain('Firefox');
});
});
describe('Response.headers', function () {
it('should work', async () => {
const { page, server } = getTestState();
server.setRoute('/empty.html', (req, res) => {
res.setHeader('foo', 'bar');
res.end();
});
const response = await page.goto(server.EMPTY_PAGE);
expect(response.headers()['foo']).toBe('bar');
});
});
describeFailsFirefox('Request.initiator', () => {
it('should return the initiator', async () => {
const { page, server } = getTestState();
const initiators = new Map();
page.on('request', (request) =>
initiators.set(request.url().split('/').pop(), request.initiator())
);
await page.goto(server.PREFIX + '/initiator.html');
expect(initiators.get('initiator.html').type).toBe('other');
expect(initiators.get('initiator.js').type).toBe('parser');
expect(initiators.get('initiator.js').url).toBe(
server.PREFIX + '/initiator.html'
);
expect(initiators.get('frame.html').type).toBe('parser');
expect(initiators.get('frame.html').url).toBe(
server.PREFIX + '/initiator.html'
);
expect(initiators.get('script.js').type).toBe('parser');
expect(initiators.get('script.js').url).toBe(
server.PREFIX + '/frames/frame.html'
);
expect(initiators.get('style.css').type).toBe('parser');
expect(initiators.get('style.css').url).toBe(
server.PREFIX + '/frames/frame.html'
);
expect(initiators.get('initiator.js').type).toBe('parser');
expect(initiators.get('injectedfile.js').type).toBe('script');
expect(initiators.get('injectedfile.js').stack.callFrames[0].url).toBe(
server.PREFIX + '/initiator.js'
);
expect(initiators.get('injectedstyle.css').type).toBe('script');
expect(initiators.get('injectedstyle.css').stack.callFrames[0].url).toBe(
server.PREFIX + '/initiator.js'
);
expect(initiators.get('initiator.js').url).toBe(
server.PREFIX + '/initiator.html'
);
});
});
describeFailsFirefox('Response.fromCache', function () {
it('should return |false| for non-cached content', async () => {
const { page, server } = getTestState();
const response = await page.goto(server.EMPTY_PAGE);
expect(response.fromCache()).toBe(false);
});
it('should work', async () => {
const { page, server } = getTestState();
const responses = new Map();
page.on(
'response',
(r) =>
!utils.isFavicon(r.request()) &&
responses.set(r.url().split('/').pop(), r)
);
// Load and re-load to make sure it's cached.
await page.goto(server.PREFIX + '/cached/one-style.html');
await page.reload();
expect(responses.size).toBe(2);
expect(responses.get('one-style.css').status()).toBe(200);
expect(responses.get('one-style.css').fromCache()).toBe(true);
expect(responses.get('one-style.html').status()).toBe(304);
expect(responses.get('one-style.html').fromCache()).toBe(false);
});
});
describeFailsFirefox('Response.fromServiceWorker', function () {
it('should return |false| for non-service-worker content', async () => {
const { page, server } = getTestState();
const response = await page.goto(server.EMPTY_PAGE);
expect(response.fromServiceWorker()).toBe(false);
});
it('Response.fromServiceWorker', async () => {
const { page, server } = getTestState();
const responses = new Map();
page.on(
'response',
(r) => !utils.isFavicon(r) && responses.set(r.url().split('/').pop(), r)
);
// Load and re-load to make sure serviceworker is installed and running.
await page.goto(server.PREFIX + '/serviceworkers/fetch/sw.html', {
waitUntil: 'networkidle2',
});
await page.evaluate(async () => await globalThis.activationPromise);
await page.reload();
expect(responses.size).toBe(2);
expect(responses.get('sw.html').status()).toBe(200);
expect(responses.get('sw.html').fromServiceWorker()).toBe(true);
expect(responses.get('style.css').status()).toBe(200);
expect(responses.get('style.css').fromServiceWorker()).toBe(true);
});
});
describeFailsFirefox('Request.postData', function () {
it('should work', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
server.setRoute('/post', (req, res) => res.end());
let request = null;
page.on('request', (r) => {
if (!utils.isFavicon(r)) request = r;
});
await page.evaluate(() =>
fetch('./post', {
method: 'POST',
body: JSON.stringify({ foo: 'bar' }),
})
);
expect(request).toBeTruthy();
expect(request.postData()).toBe('{"foo":"bar"}');
});
it('should be |undefined| when there is no post data', async () => {
const { page, server } = getTestState();
const response = await page.goto(server.EMPTY_PAGE);
expect(response.request().postData()).toBe(undefined);
});
});
describeFailsFirefox('Response.text', function () {
it('should work', async () => {
const { page, server } = getTestState();
const response = await page.goto(server.PREFIX + '/simple.json');
const responseText = (await response.text()).trimEnd();
expect(responseText).toBe('{"foo": "bar"}');
});
it('should return uncompressed text', async () => {
const { page, server } = getTestState();
server.enableGzip('/simple.json');
const response = await page.goto(server.PREFIX + '/simple.json');
expect(response.headers()['content-encoding']).toBe('gzip');
const responseText = (await response.text()).trimEnd();
expect(responseText).toBe('{"foo": "bar"}');
});
it('should throw when requesting body of redirected response', async () => {
const { page, server } = getTestState();
server.setRedirect('/foo.html', '/empty.html');
const response = await page.goto(server.PREFIX + '/foo.html');
const redirectChain = response.request().redirectChain();
expect(redirectChain.length).toBe(1);
const redirected = redirectChain[0].response();
expect(redirected.status()).toBe(302);
let error = null;
await redirected.text().catch((error_) => (error = error_));
expect(error.message).toContain(
'Response body is unavailable for redirect responses'
);
});
it('should wait until response completes', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
// Setup server to trap request.
let serverResponse = null;
server.setRoute('/get', (req, res) => {
serverResponse = res;
// In Firefox, |fetch| will be hanging until it receives |Content-Type| header
// from server.
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.write('hello ');
});
// Setup page to trap response.
let requestFinished = false;
page.on(
'requestfinished',
(r) => (requestFinished = requestFinished || r.url().includes('/get'))
);
// send request and wait for server response
const [pageResponse] = await Promise.all([
page.waitForResponse((r) => !utils.isFavicon(r.request())),
page.evaluate(() => fetch('./get', { method: 'GET' })),
server.waitForRequest('/get'),
]);
expect(serverResponse).toBeTruthy();
expect(pageResponse).toBeTruthy();
expect(pageResponse.status()).toBe(200);
expect(requestFinished).toBe(false);
const responseText = pageResponse.text();
// Write part of the response and wait for it to be flushed.
await new Promise((x) => serverResponse.write('wor', x));
// Finish response.
await new Promise((x) => serverResponse.end('ld!', x));
expect(await responseText).toBe('hello world!');
});
});
describeFailsFirefox('Response.json', function () {
it('should work', async () => {
const { page, server } = getTestState();
const response = await page.goto(server.PREFIX + '/simple.json');
expect(await response.json()).toEqual({ foo: 'bar' });
});
});
describeFailsFirefox('Response.buffer', function () {
it('should work', async () => {
const { page, server } = getTestState();
const response = await page.goto(server.PREFIX + '/pptr.png');
const imageBuffer = fs.readFileSync(
path.join(__dirname, 'assets', 'pptr.png')
);
const responseBuffer = await response.buffer();
expect(responseBuffer.equals(imageBuffer)).toBe(true);
});
it('should work with compression', async () => {
const { page, server } = getTestState();
server.enableGzip('/pptr.png');
const response = await page.goto(server.PREFIX + '/pptr.png');
const imageBuffer = fs.readFileSync(
path.join(__dirname, 'assets', 'pptr.png')
);
const responseBuffer = await response.buffer();
expect(responseBuffer.equals(imageBuffer)).toBe(true);
});
it('should throw if the response does not have a body', async () => {
const { page, server } = getTestState();
await page.goto(server.PREFIX + '/empty.html');
server.setRoute('/test.html', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'x-ping');
res.end('Hello World');
});
const url = server.CROSS_PROCESS_PREFIX + '/test.html';
const responsePromise = new Promise<HTTPResponse>((resolve) => {
page.on('response', (response) => {
// Get the preflight response.
if (
response.request().method() === 'OPTIONS' &&
response.url() === url
) {
resolve(response);
}
});
});
// Trigger a request with a preflight.
await page.evaluate<(src: string) => void>(async (src) => {
const response = await fetch(src, {
method: 'POST',
headers: { 'x-ping': 'pong' },
});
return response;
}, url);
const response = await responsePromise;
await expect(response.buffer()).rejects.toThrowError(
'Could not load body for this request. This might happen if the request is a preflight request.'
);
});
});
describe('Response.statusText', function () {
it('should work', async () => {
const { page, server } = getTestState();
server.setRoute('/cool', (req, res) => {
res.writeHead(200, 'cool!');
res.end();
});
const response = await page.goto(server.PREFIX + '/cool');
expect(response.statusText()).toBe('cool!');
});
it('handles missing status text', async () => {
const { page, server } = getTestState();
server.setRoute('/nostatus', (req, res) => {
res.writeHead(200, '');
res.end();
});
const response = await page.goto(server.PREFIX + '/nostatus');
expect(response.statusText()).toBe('');
});
});
describeFailsFirefox('Response.timing', function () {
it('returns timing information', async () => {
const { page, server } = getTestState();
const responses = [];
page.on('response', (response) => responses.push(response));
await page.goto(server.EMPTY_PAGE);
expect(responses.length).toBe(1);
expect(responses[0].timing().receiveHeadersEnd).toBeGreaterThan(0);
});
});
describeFailsFirefox('Network Events', function () {
it('Page.Events.Request', async () => {
const { page, server } = getTestState();
const requests = [];
page.on('request', (request) => requests.push(request));
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests[0].url()).toBe(server.EMPTY_PAGE);
expect(requests[0].resourceType()).toBe('document');
expect(requests[0].method()).toBe('GET');
expect(requests[0].response()).toBeTruthy();
expect(requests[0].frame() === page.mainFrame()).toBe(true);
expect(requests[0].frame().url()).toBe(server.EMPTY_PAGE);
});
it('Page.Events.RequestServedFromCache', async () => {
const { page, server } = getTestState();
const cached = [];
page.on('requestservedfromcache', (r) =>
cached.push(r.url().split('/').pop())
);
await page.goto(server.PREFIX + '/cached/one-style.html');
expect(cached).toEqual([]);
await page.reload();
expect(cached).toEqual(['one-style.css']);
});
it('Page.Events.Response', async () => {
const { page, server } = getTestState();
const responses = [];
page.on('response', (response) => responses.push(response));
await page.goto(server.EMPTY_PAGE);
expect(responses.length).toBe(1);
expect(responses[0].url()).toBe(server.EMPTY_PAGE);
expect(responses[0].status()).toBe(200);
expect(responses[0].ok()).toBe(true);
expect(responses[0].request()).toBeTruthy();
const remoteAddress = responses[0].remoteAddress();
// Either IPv6 or IPv4, depending on environment.
expect(
remoteAddress.ip.includes('::1') || remoteAddress.ip === '127.0.0.1'
).toBe(true);
expect(remoteAddress.port).toBe(server.PORT);
});
it('Page.Events.RequestFailed', async () => {
const { page, server, isChrome } = getTestState();
await page.setRequestInterception(true);
page.on('request', (request) => {
if (request.url().endsWith('css')) request.abort();
else request.continue();
});
const failedRequests = [];
page.on('requestfailed', (request) => failedRequests.push(request));
await page.goto(server.PREFIX + '/one-style.html');
expect(failedRequests.length).toBe(1);
expect(failedRequests[0].url()).toContain('one-style.css');
expect(failedRequests[0].response()).toBe(null);
expect(failedRequests[0].resourceType()).toBe('stylesheet');
if (isChrome)
expect(failedRequests[0].failure().errorText).toBe('net::ERR_FAILED');
else
expect(failedRequests[0].failure().errorText).toBe('NS_ERROR_FAILURE');
expect(failedRequests[0].frame()).toBeTruthy();
});
it('Page.Events.RequestFinished', async () => {
const { page, server } = getTestState();
const requests = [];
page.on('requestfinished', (request) => requests.push(request));
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests[0].url()).toBe(server.EMPTY_PAGE);
expect(requests[0].response()).toBeTruthy();
expect(requests[0].frame() === page.mainFrame()).toBe(true);
expect(requests[0].frame().url()).toBe(server.EMPTY_PAGE);
});
it('should fire events in proper order', async () => {
const { page, server } = getTestState();
const events = [];
page.on('request', () => events.push('request'));
page.on('response', () => events.push('response'));
page.on('requestfinished', () => events.push('requestfinished'));
await page.goto(server.EMPTY_PAGE);
expect(events).toEqual(['request', 'response', 'requestfinished']);
});
it('should support redirects', async () => {
const { page, server } = getTestState();
const events = [];
page.on('request', (request) =>
events.push(`${request.method()} ${request.url()}`)
);
page.on('response', (response) =>
events.push(`${response.status()} ${response.url()}`)
);
page.on('requestfinished', (request) =>
events.push(`DONE ${request.url()}`)
);
page.on('requestfailed', (request) =>
events.push(`FAIL ${request.url()}`)
);
server.setRedirect('/foo.html', '/empty.html');
const FOO_URL = server.PREFIX + '/foo.html';
const response = await page.goto(FOO_URL);
expect(events).toEqual([
`GET ${FOO_URL}`,
`302 ${FOO_URL}`,
`DONE ${FOO_URL}`,
`GET ${server.EMPTY_PAGE}`,
`200 ${server.EMPTY_PAGE}`,
`DONE ${server.EMPTY_PAGE}`,
]);
// Check redirect chain
const redirectChain = response.request().redirectChain();
expect(redirectChain.length).toBe(1);
expect(redirectChain[0].url()).toContain('/foo.html');
expect(redirectChain[0].response().remoteAddress().port).toBe(
server.PORT
);
});
});
describe('Request.isNavigationRequest', () => {
itFailsFirefox('should work', async () => {
const { page, server } = getTestState();
const requests = new Map();
page.on('request', (request) =>
requests.set(request.url().split('/').pop(), request)
);
server.setRedirect('/rrredirect', '/frames/one-frame.html');
await page.goto(server.PREFIX + '/rrredirect');
expect(requests.get('rrredirect').isNavigationRequest()).toBe(true);
expect(requests.get('one-frame.html').isNavigationRequest()).toBe(true);
expect(requests.get('frame.html').isNavigationRequest()).toBe(true);
expect(requests.get('script.js').isNavigationRequest()).toBe(false);
expect(requests.get('style.css').isNavigationRequest()).toBe(false);
});
itFailsFirefox('should work with request interception', async () => {
const { page, server } = getTestState();
const requests = new Map();
page.on('request', (request) => {
requests.set(request.url().split('/').pop(), request);
request.continue();
});
await page.setRequestInterception(true);
server.setRedirect('/rrredirect', '/frames/one-frame.html');
await page.goto(server.PREFIX + '/rrredirect');
expect(requests.get('rrredirect').isNavigationRequest()).toBe(true);
expect(requests.get('one-frame.html').isNavigationRequest()).toBe(true);
expect(requests.get('frame.html').isNavigationRequest()).toBe(true);
expect(requests.get('script.js').isNavigationRequest()).toBe(false);
expect(requests.get('style.css').isNavigationRequest()).toBe(false);
});
itFailsFirefox('should work when navigating to image', async () => {
const { page, server } = getTestState();
const requests = [];
page.on('request', (request) => requests.push(request));
await page.goto(server.PREFIX + '/pptr.png');
expect(requests[0].isNavigationRequest()).toBe(true);
});
});
describeFailsFirefox('Page.setExtraHTTPHeaders', function () {
it('should work', async () => {
const { page, server } = getTestState();
await page.setExtraHTTPHeaders({
foo: 'bar',
});
const [request] = await Promise.all([
server.waitForRequest('/empty.html'),
page.goto(server.EMPTY_PAGE),
]);
expect(request.headers['foo']).toBe('bar');
});
it('should throw for non-string header values', async () => {
const { page } = getTestState();
let error = null;
try {
// @ts-expect-error purposeful bad input
await page.setExtraHTTPHeaders({ foo: 1 });
} catch (error_) {
error = error_;
}
expect(error.message).toBe(
'Expected value of header "foo" to be String, but "number" is found.'
);
});
});
describeFailsFirefox('Page.authenticate', function () {
it('should work', async () => {
const { page, server } = getTestState();
server.setAuth('/empty.html', 'user', 'pass');
let response;
try {
response = await page.goto(server.EMPTY_PAGE);
expect(response.status()).toBe(401);
} catch (error) {
// In headful, an error is thrown instead of 401.
if (!error.message.startsWith('net::ERR_INVALID_AUTH_CREDENTIALS')) {
throw error;
}
}
await page.authenticate({
username: 'user',
password: 'pass',
});
response = await page.reload();
expect(response.status()).toBe(200);
});
it('should fail if wrong credentials', async () => {
const { page, server } = getTestState();
// Use unique user/password since Chrome caches credentials per origin.
server.setAuth('/empty.html', 'user2', 'pass2');
await page.authenticate({
username: 'foo',
password: 'bar',
});
const response = await page.goto(server.EMPTY_PAGE);
expect(response.status()).toBe(401);
});
it('should allow disable authentication', async () => {
const { page, server } = getTestState();
// Use unique user/password since Chrome caches credentials per origin.
server.setAuth('/empty.html', 'user3', 'pass3');
await page.authenticate({
username: 'user3',
password: 'pass3',
});
let response = await page.goto(server.EMPTY_PAGE);
expect(response.status()).toBe(200);
await page.authenticate(null);
// Navigate to a different origin to bust Chrome's credential caching.
try {
response = await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html');
expect(response.status()).toBe(401);
} catch (error) {
// In headful, an error is thrown instead of 401.
if (!error.message.startsWith('net::ERR_INVALID_AUTH_CREDENTIALS')) {
throw error;
}
}
});
it('should not disable caching', async () => {
const { page, server } = getTestState();
// Use unique user/password since Chrome caches credentials per origin.
server.setAuth('/cached/one-style.css', 'user4', 'pass4');
server.setAuth('/cached/one-style.html', 'user4', 'pass4');
await page.authenticate({
username: 'user4',
password: 'pass4',
});
const responses = new Map();
page.on('response', (r) => responses.set(r.url().split('/').pop(), r));
// Load and re-load to make sure it's cached.
await page.goto(server.PREFIX + '/cached/one-style.html');
await page.reload();
expect(responses.get('one-style.css').status()).toBe(200);
expect(responses.get('one-style.css').fromCache()).toBe(true);
expect(responses.get('one-style.html').status()).toBe(304);
expect(responses.get('one-style.html').fromCache()).toBe(false);
});
});
describeFailsFirefox('raw network headers', async () => {
it('Same-origin set-cookie navigation', async () => {
const { page, server } = getTestState();
const setCookieString = 'foo=bar';
server.setRoute('/empty.html', (req, res) => {
res.setHeader('set-cookie', setCookieString);
res.end('hello world');
});
const response = await page.goto(server.EMPTY_PAGE);
expect(response.headers()['set-cookie']).toBe(setCookieString);
});
it('Same-origin set-cookie subresource', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
const setCookieString = 'foo=bar';
server.setRoute('/foo', (req, res) => {
res.setHeader('set-cookie', setCookieString);
res.end('hello world');
});
const responsePromise = new Promise<HTTPResponse>((resolve) =>
page.on('response', (response) => resolve(response))
);
page.evaluate(() => {
const xhr = new XMLHttpRequest();
xhr.open('GET', '/foo');
xhr.send();
});
const subresourceResponse = await responsePromise;
expect(subresourceResponse.headers()['set-cookie']).toBe(setCookieString);
});
it('Cross-origin set-cookie', async () => {
const { httpsServer, puppeteer, defaultBrowserOptions } = getTestState();
const browser = await puppeteer.launch({
...defaultBrowserOptions,
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
try {
await page.goto(httpsServer.PREFIX + '/empty.html');
const setCookieString = 'hello=world';
httpsServer.setRoute('/setcookie.html', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('set-cookie', setCookieString);
res.end();
});
await page.goto(httpsServer.PREFIX + '/setcookie.html');
const response = await new Promise<HTTPResponse>((resolve) => {
page.on('response', resolve);
const url = httpsServer.CROSS_PROCESS_PREFIX + '/setcookie.html';
page.evaluate<(src: string) => void>((src) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', src);
xhr.send();
}, url);
});
expect(response.headers()['set-cookie']).toBe(setCookieString);
} finally {
await page.close();
await browser.close();
}
});
});
});