-
-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathPage.php
More file actions
696 lines (591 loc) · 18.8 KB
/
Page.php
File metadata and controls
696 lines (591 loc) · 18.8 KB
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
<?php
declare(strict_types=1);
namespace Pest\Browser\Playwright;
use Generator;
use Pest\Browser\Execution;
use Pest\Browser\Support\ImageDiffView;
use Pest\Browser\Support\JavaScriptSerializer;
use Pest\Browser\Support\Screenshot;
use Pest\Browser\Support\Selector;
use Pest\Browser\Support\Shell;
use Pest\TestSuite;
use PHPUnit\Framework\ExpectationFailedException;
use RuntimeException;
/**
* @internal
*/
final class Page
{
use Concerns\InteractsWithPlaywright;
/**
* Whether the page has been closed.
*/
private bool $closed = false;
/**
* Enable or disable strict locators.
*/
private bool $strictLocators = true;
/**
* Creates a new page instance.
*/
public function __construct(
private readonly Context $context,
private readonly string $guid,
private readonly string $frameGuid,
) {
//
}
/**
* Get the browser context.
*/
public function context(): Context
{
return $this->context;
}
/**
* Get the current URL of the page.
*/
public function url(): string
{
$url = Execution::instance()->waitForExpectation(
fn (): mixed => $this->evaluate('() => window.location.href'),
);
assert(is_string($url), 'Expected URL to be a string, got: '.gettype($url));
return $url;
}
/**
* Performs the given callback in unstrict mode.
*
* @template TReturn
*
* @param callable(Page): TReturn $callback
* @return TReturn
*/
public function unstrict(callable $callback): mixed
{
try {
$this->strictLocators = false;
return $callback($this);
} finally {
$this->strictLocators = true;
}
}
/**
* Navigates to the given URL.
*
* @param array<string, mixed> $options
*/
public function goto(string $url, array $options = []): self
{
$response = $this->sendMessage('goto', [
...['url' => $url, 'waitUntil' => 'load'],
...$options,
]);
$this->processVoidResponse($response);
return $this;
}
/**
* Returns the meta title.
*/
public function title(): string
{
$response = $this->sendMessage('title');
return $this->processStringResponse($response);
}
/**
* Finds an element matching the specified selector.
*
* @deprecated Use locator($selector)->elementHandle() instead for Element compatibility, or use locator($selector) for Locator-first approach
*/
public function querySelector(string $selector): ?Element
{
return $this->locator($selector)->elementHandle();
}
/**
* Finds all elements matching the specified selector.
*
* @return Element[]
*/
public function querySelectorAll(string $selector): array
{
$response = $this->sendMessage('querySelectorAll', ['selector' => $selector]);
$elements = [];
/** @var array{method?: string|null, params: array{type?: string|null, guid?: string}} $message */
foreach ($response as $message) {
if (
isset($message['method'], $message['params']['type'], $message['params']['guid'])
&& $message['method'] === '__create__'
&& $message['params']['type'] === 'ElementHandle'
) {
$elements[] = new Element($message['params']['guid']);
}
}
return $elements;
}
/**
* Create a locator for the specified selector.
*/
public function locator(string $selector): Locator
{
return new Locator($this->frameGuid, $selector, $this->strictLocators);
}
/**
* Create a locator that matches elements by role.
*
* @param array<string, string|bool> $params
*/
public function getByRole(string $role, array $params = []): Locator
{
return $this->locator(Selector::getByRoleSelector($role, $params));
}
/**
* Create a locator that matches elements by test ID.
*/
public function getByTestId(string $testId): Locator
{
$testIdAttributeName = 'data-testid';
return $this->locator(Selector::getByTestIdSelector($testIdAttributeName, $testId));
}
/**
* Create a locator that matches elements by alt text.
*/
public function getByAltText(string $text, bool $exact = false): Locator
{
return $this->locator(Selector::getByAltTextSelector($text, $exact));
}
/**
* Create a locator that matches elements by label text.
*/
public function getByLabel(string $text, bool $exact = false): Locator
{
return $this->locator(Selector::getByLabelSelector($text, $exact));
}
/**
* Create a locator that matches elements by placeholder text.
*/
public function getByPlaceholder(string $text, bool $exact = false): Locator
{
return $this->locator(Selector::getByPlaceholderSelector($text, $exact));
}
/**
* Create a locator that matches elements by text content.
*/
public function getByText(string $text, bool $exact = false): Locator
{
return $this->locator(Selector::getByTextSelector($text, $exact));
}
/**
* Create a locator that matches elements by title attribute.
*/
public function getByTitle(string $text, bool $exact = false): Locator
{
return $this->locator(Selector::getByTitleSelector($text, $exact));
}
/**
* Gets the full HTML contents of the page, including the doctype.
*/
public function content(): string
{
$response = $this->sendMessage('content');
return $this->processStringResponse($response);
}
/**
* Gets the text content of the body element.
*/
public function textContent(): ?string
{
return $this->locator('body')->textContent();
}
/**
* Waits for the specified load state.
*/
public function waitForLoadState(string $state = 'load'): self
{
Client::instance()->execute(
$this->guid,
'waitForLoadState',
['state' => $state]
);
return $this;
}
/**
* Waits for a JavaScript function to return true.
*
* @param mixed $arg Optional argument to pass to the function
*/
public function waitForFunction(string $content, mixed $arg = null): self
{
$params = [
'expression' => $content,
'arg' => JavaScriptSerializer::serializeArgument($arg),
];
Client::instance()->execute(
$this->guid,
'waitForFunction',
$params
);
return $this;
}
/**
* Waits for navigation to the specified URL.
*/
public function waitForURL(string $url): self
{
Client::instance()->execute(
$this->guid,
'waitForURL',
['url' => $url]
);
return $this;
}
/**
* Adds a script tag to the page.
*/
public function addStyleTag(string $content): self
{
$response = $this->sendMessage('addStyleTag', ['content' => $content]);
$this->processVoidResponse($response);
return $this;
}
/**
* Waits for the selector to satisfy state option.
*
* @param array<string, mixed>|null $options Additional options like state, strict, timeout
*/
public function waitForSelector(string $selector, ?array $options = null): ?Element
{
$locator = $this->locator($selector);
$locator->waitFor($options);
return $locator->elementHandle();
}
/**
* Sets the viewport size and resizes the page.
*/
public function setViewportSize(int $width, int $height): self
{
$viewportSize = ['viewportSize' => ['width' => $width, 'height' => $height]];
$response = $this->sendMessage('setViewportSize', $viewportSize);
$this->processVoidResponse($response);
return $this;
}
/**
* Returns the viewport size.
*
* @return array{width: int, height: int}
*/
public function viewportSize(): array
{
/** @var array{width: int, height: int} $result */
$result = $this->evaluate('() => ({ width: window.innerWidth, height: window.innerHeight })');
return $result;
}
/**
* Sets the content of the page.
*/
public function setContent(string $html): self
{
$response = $this->sendMessage('setContent', ['html' => $html]);
$this->processVoidResponse($response);
return $this;
}
/**
* Evaluates a JavaScript expression in the page context.
*/
public function evaluate(string $pageFunction, mixed $arg = null): mixed
{
$params = [
'expression' => $pageFunction,
'arg' => JavaScriptSerializer::serializeArgument($arg),
];
$response = $this->sendMessage('evaluateExpression', $params);
return $this->processResultResponse($response);
}
/**
* Evaluates a JavaScript expression and returns a JSHandle.
*/
public function evaluateHandle(string $pageFunction, mixed $arg = null): JSHandle
{
$params = [
'expression' => $pageFunction,
'arg' => JavaScriptSerializer::serializeArgument($arg),
];
$response = $this->sendMessage('evaluateExpressionHandle', $params);
foreach ($response as $message) {
if (
is_array($message) && is_array($message['params'] ?? null)
&& isset($message['method'], $message['params']['type'], $message['params']['guid'])
&& $message['method'] === '__create__'
&& $message['params']['type'] === 'JSHandle'
) {
return new JSHandle((string) $message['params']['guid']); // @phpstan-ignore-line
}
if (
is_array($message)
&& is_array($message['result'] ?? null)
&& isset($message['result']['handle'])
) {
return new JSHandle($message['result']['handle']['guid']); // @phpstan-ignore-line
}
}
throw new RuntimeException('Failed to create JSHandle from evaluate response');
}
/**
* Navigates to the next page in the history.
*/
public function forward(): self
{
$response = $this->sendMessage('goForward');
$this->processVoidResponse($response);
return $this;
}
/**
* Navigates to the previous page in the history.
*/
public function back(): self
{
$response = $this->sendMessage('goBack');
$this->processVoidResponse($response);
return $this;
}
/**
* Reloads the current page.
*/
public function reload(): self
{
$response = $this->sendMessage('reload', ['waitUntil' => 'load']);
$this->processVoidResponse($response);
return $this;
}
/**
* Make screenshot of the page.
*/
public function screenshot(bool $fullPage = true, ?string $filename = null, ?string $scale = null): ?string
{
$binary = $this->screenshotBinary($fullPage, $scale);
if ($binary === null) {
return null;
}
return Screenshot::save($binary, $filename);
}
/**
* Make screenshot of a specific element.
*/
public function screenshotElement(string $selector, ?string $filename = null, ?string $scale = null): string
{
$locator = $this->locator($selector);
$binary = $locator->screenshot([
'scale' => $scale ?? 'css',
]);
return Screenshot::save($binary, $filename);
}
/**
* Get the console logs from the page, if any.
*
* @return array<int, array{message: string}>
*/
public function consoleLogs(): array
{
$consoleLogs = $this->evaluate('window.__pestBrowser.consoleLogs || []');
/** @var array<int, array{message: string}> $consoleLogs */
return $consoleLogs;
}
/**
* Get the broken images from the page, if any.
*
* @return array<int, string>
*/
public function brokenImages(): array
{
$brokenImages = $this->evaluate(<<<'JS'
() => {
return Array.from(document.images)
.filter(img => img.complete && img.naturalWidth === 0)
.map(img => img.src);
}
JS);
/** @var array<int, string> $brokenImages */
return $brokenImages;
}
/**
* Get the JavaScript errors from the page, if any.
*
* @return array<int, array{message: string}>
*/
public function javaScriptErrors(): array
{
$jsErrors = $this->evaluate('window.__pestBrowser.jsErrors || []');
/** @var array<int, array{message: string}> $jsErrors */
return $jsErrors;
}
/**
* Make a screenshot of the page and compare it with the expected one.
*
* @throws ExpectationFailedException
*/
public function expectScreenshot(bool $fullPage, bool $openDiff): void
{
$actualImageBlob = $this->screenshotBinary($fullPage);
assert(is_string($actualImageBlob), 'Unable to screenshot');
try {
expect($actualImageBlob)->toMatchSnapshot();
} catch (ExpectationFailedException) {
[$snapshotName, $expectedImageBlob] = TestSuite::getInstance()->snapshots->get();
$response = Client::instance()->execute(
$this->guid,
'expectScreenshot',
[
...$this->screenshotOptions($fullPage),
'expected' => $expectedImageBlob,
'timeout' => 30000,
'isNot' => false,
'comparisonMethod' => 'pixelmatch',
'threshold' => 0.3,
'maxDiffPixels' => 300,
'maxDiffPixelRatio' => 0.01,
'detectAntialiasing' => true,
'forceSameDimensions' => true,
]
);
$snapshotName = pathinfo($snapshotName, PATHINFO_FILENAME);
/** @var array{result: array{diff: string|null}} $message */
foreach ($response as $message) {
if (isset($message['result']['diff'])) {
$this->createImageDiffView(
$snapshotName,
$expectedImageBlob,
$actualImageBlob,
$message['result']['diff'],
$openDiff
);
throw new ExpectationFailedException(<<<'EOT'
Screenshot does not match the last one.
- Expected? Update the snapshots with [--update-snapshots].
- Not expected? Re-run the test with [--diff] to see the differences.
EOT
);
}
}
$this->createImageDiffView(
$snapshotName,
$expectedImageBlob,
$actualImageBlob,
ImageDiffView::missingImage(),
$openDiff,
);
throw new ExpectationFailedException(<<<'EOT'
Screenshot does not match the last one.
- Expected? Update the snapshots with [--update-snapshots].
EOT,
);
}
}
/**
* Closes the page.
*/
public function close(): void
{
if ($this->context->browser()->isClosed()
|| $this->context->isClosed()
|| $this->closed) {
return;
}
$response = $this->sendMessage('close');
$this->processVoidResponse($response);
$this->closed = true;
}
/**
* Checks if the page is closed.
*/
public function isClosed(): bool
{
return $this->closed;
}
/**
* Screenshots the page and returns the binary data.
*/
private function screenshotBinary(bool $fullPage = true, ?string $scale = null): ?string
{
$response = Client::instance()->execute(
$this->guid,
'screenshot',
$this->screenshotOptions($fullPage, $scale)
);
/** @var array{result: array{binary: string|null}} $message */
foreach ($response as $message) {
if (isset($message['result']['binary'])) {
return $message['result']['binary'];
}
}
return null;
}
/**
* Send a message to the frame (for frame-related operations)
*
* @param array<string, mixed> $params
*/
private function sendMessage(string $method, array $params = []): Generator
{
// Use frame GUID for frame-related operations, page GUID for page-level operations
$targetGuid = $this->isPageLevelOperation($method) ? $this->guid : $this->frameGuid;
return Client::instance()->execute($targetGuid, $method, $params);
}
/**
* Determine if an operation should use the page GUID vs frame GUID
*/
private function isPageLevelOperation(string $method): bool
{
$pageLevelOperations = [
'close',
'Network.setExtraHTTPHeaders',
'goForward',
'goBack',
'reload',
'screenshot',
'waitForLoadState',
'waitForURL',
'keyboardDown',
'keyboardUp',
'setViewportSize',
'viewportSize',
];
return in_array($method, $pageLevelOperations, true);
}
/**
* @return array<string, mixed>
*/
private function screenshotOptions(bool $fullPage = true, ?string $scale = null): array
{
return [
'type' => 'png',
'fullPage' => $fullPage,
'caret' => 'hide',
'animations' => 'disabled',
'scale' => $scale ?? 'css', // 'css' or 'device'
];
}
/**
* Create an HTML view for the image diff.
*/
private function createImageDiffView(
string $snapshotName,
string $expectedImageBlob,
string $actualImageBlob,
string $diff,
bool $openDiff
): void {
$imageDiffViewDir = Screenshot::dir().'/ImageDiffView';
if (is_dir($imageDiffViewDir) === false) {
mkdir($imageDiffViewDir, 0755, true);
}
$imageDiffViewPath = $imageDiffViewDir.'/'.$snapshotName.'.html';
file_put_contents($imageDiffViewPath, ImageDiffView::generate(
$expectedImageBlob,
$actualImageBlob,
$diff,
test()->name() // @phpstan-ignore-line
));
if ($openDiff) {
Shell::open($imageDiffViewPath);
}
}
}