diff --git a/CHANGELOG.md b/CHANGELOG.md index be94a4ee..9df8944d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ - WebP screenshots through `type: 'webp'` in `ScreenshotOptions` and `LocatorScreenshotOptions` (#206) - `ScreenshotOptions::$style` applies CSS while a page screenshot is taken, like `LocatorScreenshotOptions::$style` (#210) - `Page::screenshotAuto()` accepts `ScreenshotOptions`, like `Page::screenshot()` (#210) +- `PageEventHandlerInterface::onDownload()` receives each `Download` a page starts (#211) +- `PageInterface::waitForDownload()` runs an action and returns the `Download` it starts, with `path()`, `saveAs()`, `failure()`, `cancel()`, `delete()` and `createReadStream()` working end to end (#211) ### Changed - `ScreenshotHelper::cleanupOldScreenshots()` and `getDirectoryInfo()` include `.jpeg`, `.jpg` and `.webp` files along with `.png`; cleanup now deletes old files of these formats (#208) diff --git a/bin/lib/handlers.js b/bin/lib/handlers.js index c2d9b1f4..7f05b18a 100644 --- a/bin/lib/handlers.js +++ b/bin/lib/handlers.js @@ -1,3 +1,4 @@ +const fs = require('fs/promises'); const { logger, ErrorHandler, CommandRegistry, BaseHandler, PromiseUtils, FrameUtils, RouteUtils } = require('./core'); const { globalCoordinator } = require('./coordination'); const { PopupCoordinator } = require('./popup-coordinator'); @@ -460,6 +461,7 @@ class PageHandler extends BaseHandler { frames: () => this.getFrames(page), frame: () => this.getFrame(page, command), waitForPopup: () => this.waitForPopup(page, command), + waitForDownload: () => this.waitForDownload(page, command), bringToFront: () => page.bringToFront(), ariaSnapshot: () => PromiseUtils.wrapValue(page.ariaSnapshot(command.options)), hideHighlight: () => page.hideHighlight(), @@ -706,6 +708,45 @@ class PageHandler extends BaseHandler { return FrameUtils.selectorForNativeFrame(frame, mainFrame); } + // Same callback coordination as waitForPopup: the listener is armed first, + // then PHP runs the action that starts the download. + async waitForDownload(page, command) { + const requestId = command.requestId || this.generateId('download_req'); + const timeout = command.timeout ?? 30000; + const registerDownload = this.registerDownload; + + globalCoordinator.registerAsyncCommand(requestId, [ + { + name: 'setupListener', + handler: async () => { + const downloadPromise = page.waitForEvent('download', { timeout }); + // PHP may still be running the action when this rejects. Observe it + // now; awaiting the promise in the next phase still throws it. + downloadPromise.catch(() => {}); + return { downloadPromise }; + }, + waitForCallback: true, + callbackType: 'readyForAction' + }, + { + name: 'waitForDownload', + handler: async (data) => { + const download = await data.downloadPromise; + + return { + page: undefined, + downloadPromise: undefined, + timeout: undefined, + ...registerDownload(download, page) + }; + }, + waitForCallback: false + } + ]); + + return await globalCoordinator.executeNextPhase(requestId, { page, timeout }); + } + async waitForPopup(page, command) { const timeout = command.timeout || 30000; const requestId = command.requestId || this.generateId('popup_req'); @@ -1157,6 +1198,25 @@ class SelectorsHandler extends BaseHandler { } } +class DownloadHandler extends BaseHandler { + async handle(command, method) { + const download = this.validateResource(this.downloads, command.downloadId, 'Download'); + + const registry = CommandRegistry.create({ + path: async () => ({ path: await download.path() }), + saveAs: () => download.saveAs(command.path), + // Not "error": the PHP transport reads that key as a failed command. + failure: async () => ({ failure: await download.failure() }), + cancel: () => download.cancel(), + delete: () => download.delete(), + readStream: async () => ({ stream: (await fs.readFile(await download.path())).toString('base64') }) + }); + + const result = await ErrorHandler.safeExecute(() => this.executeWithRegistry(registry, method), { method, downloadId: command.downloadId }); + return this.wrapResult(result); + } +} + class VideoHandler extends BaseHandler { async handle(command, method) { const video = this.validateResource(this.videos, command.videoId, 'Video'); @@ -1175,4 +1235,4 @@ class VideoHandler extends BaseHandler { } } -module.exports = { APIRequestHandler, ContextHandler, PageHandler, LocatorHandler, InteractionHandler, FrameHandler, JSHandleHandler, SelectorsHandler, VideoHandler }; +module.exports = { APIRequestHandler, ContextHandler, PageHandler, LocatorHandler, InteractionHandler, FrameHandler, JSHandleHandler, SelectorsHandler, VideoHandler, DownloadHandler }; diff --git a/bin/playwright-server.js b/bin/playwright-server.js index a50bfa1d..c7563edc 100644 --- a/bin/playwright-server.js +++ b/bin/playwright-server.js @@ -1,6 +1,6 @@ const {chromium, firefox, webkit, request} = require('playwright'); const { logger, ErrorHandler, LspFraming, sendFramedResponse, CommandRegistry, NavigationRedirects, BaseHandler, RouteUtils } = require('./lib/core'); -const { APIRequestHandler, ContextHandler, PageHandler, LocatorHandler, InteractionHandler, FrameHandler, JSHandleHandler, SelectorsHandler, VideoHandler } = require('./lib/handlers'); +const { APIRequestHandler, ContextHandler, PageHandler, LocatorHandler, InteractionHandler, FrameHandler, JSHandleHandler, SelectorsHandler, VideoHandler, DownloadHandler } = require('./lib/handlers'); const { globalCoordinator } = require('./lib/coordination'); class PlaywrightServer extends BaseHandler { @@ -24,8 +24,10 @@ class PlaywrightServer extends BaseHandler { this.navigationRedirects = new NavigationRedirects(); this.servers = new Map(); this.videos = new Map(); + this.downloads = new Map(); + this.downloadIds = new WeakMap(); this.apiContexts = new Map(); - this.counters = { api: 0, browser: 0, context: 0, page: 0, response: 0, route: 0, element: 0, server: 0, video: 0 }; + this.counters = { api: 0, browser: 0, context: 0, page: 0, response: 0, route: 0, element: 0, server: 0, video: 0, download: 0, download_req: 0 }; } initHandlers() { @@ -33,7 +35,7 @@ class PlaywrightServer extends BaseHandler { contexts: this.contexts, contextThrottling: this.contextThrottling, pages: this.pages, apiContexts: this.apiContexts, apiRequest: request, pageContexts: this.pageContexts, dialogs: this.dialogs, elementHandles: this.elementHandles, - responses: this.responses, routes: this.routes, routeHandlers: this.routeHandlers, videos: this.videos, generateId: this.generateId.bind(this), + responses: this.responses, routes: this.routes, routeHandlers: this.routeHandlers, videos: this.videos, downloads: this.downloads, registerDownload: this.registerDownload.bind(this), generateId: this.generateId.bind(this), navigationRedirects: this.navigationRedirects, extractRequestData: this.extractRequestData.bind(this), serializeResponse: this.serializeResponse.bind(this), serializeConsoleMessage: this.serializeConsoleMessage.bind(this), @@ -49,6 +51,7 @@ class PlaywrightServer extends BaseHandler { this.jsHandleHandler = new JSHandleHandler(deps); this.selectorsHandler = new SelectorsHandler(deps); this.videoHandler = new VideoHandler(deps); + this.downloadHandler = new DownloadHandler(deps); } async handleCommand(command) { @@ -90,6 +93,7 @@ class PlaywrightServer extends BaseHandler { credentials: () => this.contextHandler.handleCredentials(command, actionMethod), screencast: () => this.pageHandler.handleScreencast(command, actionMethod), video: () => this.videoHandler.handle(command, actionMethod), + download: () => this.downloadHandler.handle(command, actionMethod), // Tracing actions are flat names (no dot), sent by the PHP Tracing class tracingStart: () => this.contextHandler.handleTracing(command, 'start'), tracingStartChunk: () => this.contextHandler.handleTracing(command, 'startChunk'), @@ -169,9 +173,9 @@ class PlaywrightServer extends BaseHandler { } setupPageEventListeners(page, pageId) { - ['console', 'dialog', 'request', 'response', 'requestfailed'].forEach(eventName => { + ['console', 'dialog', 'request', 'response', 'requestfailed', 'download'].forEach(eventName => { page.on(eventName, ErrorHandler.wrapHandler((eventData) => { - const params = this.formatEventParams(eventName, eventData); + const params = eventName === 'download' ? this.registerDownload(eventData, page) : this.formatEventParams(eventName, eventData); sendFramedResponse({ objectId: pageId, event: eventName, params }); })); }); @@ -195,6 +199,20 @@ class PlaywrightServer extends BaseHandler { context.once('close', () => RouteUtils.forgetRoutes(this.routes, this.routeHandlers, contextId)); } + // One id per download, whether PHP learns about it from the page event or from + // waitForDownload(). The file lives as long as its browser context. + registerDownload(download, page) { + let downloadId = this.downloadIds.get(download); + if (!downloadId) { + downloadId = this.generateId('download'); + this.downloadIds.set(download, downloadId); + this.downloads.set(downloadId, download); + page.context().once('close', () => this.downloads.delete(downloadId)); + } + + return { downloadId, suggestedFilename: download.suggestedFilename(), url: download.url() }; + } + registerPage(page, contextId) { const pageId = this.generateId('page'); this.pages.set(pageId, page); diff --git a/src/Download/Download.php b/src/Download/Download.php index dde84e72..adf6bb71 100644 --- a/src/Download/Download.php +++ b/src/Download/Download.php @@ -88,7 +88,7 @@ public function failure(): ?string 'downloadId' => $this->downloadId, ]); - return isset($response['error']) && is_string($response['error']) ? $response['error'] : null; + return isset($response['failure']) && is_string($response['failure']) ? $response['failure'] : null; } public function page(): PageInterface diff --git a/src/Page/Options/WaitForDownloadOptions.php b/src/Page/Options/WaitForDownloadOptions.php new file mode 100644 index 00000000..7d751efd --- /dev/null +++ b/src/Page/Options/WaitForDownloadOptions.php @@ -0,0 +1,54 @@ + + */ + public function toArray(): array + { + $options = []; + if (null !== $this->timeout) { + $options['timeout'] = $this->timeout; + } + + return $options; + } + + /** + * @param array|self $options + */ + public static function from(array|self $options = []): self + { + if ($options instanceof self) { + return $options; + } + + /** @var float|int|null $timeout */ + $timeout = $options['timeout'] ?? null; + + return new self(null === $timeout ? null : (float) $timeout); + } +} diff --git a/src/Page/Page.php b/src/Page/Page.php index fb902b86..136e0981 100644 --- a/src/Page/Page.php +++ b/src/Page/Page.php @@ -22,6 +22,8 @@ use Playwright\Console\ConsoleMessage; use Playwright\Cookie; use Playwright\Dialog\Dialog; +use Playwright\Download\Download; +use Playwright\Download\DownloadInterface; use Playwright\Event\EventDispatcherInterface; use Playwright\Exception\NetworkException; use Playwright\Exception\PlaywrightException; @@ -65,6 +67,7 @@ use Playwright\Page\Options\SetInputFilesOptions; use Playwright\Page\Options\StyleTagOptions; use Playwright\Page\Options\TypeOptions; +use Playwright\Page\Options\WaitForDownloadOptions; use Playwright\Page\Options\WaitForFunctionOptions; use Playwright\Page\Options\WaitForLoadStateOptions; use Playwright\Page\Options\WaitForPopupOptions; @@ -192,6 +195,11 @@ public function dispatchEvent(string $eventName, array $params): void $this->eventHandler->publicEmit('requestfailed', [$this->createRequest($params['request'])]); } break; + case 'download': + if (is_string($params['downloadId'] ?? null)) { + $this->eventHandler->publicEmit('download', [new Download($this->transport, $this, $params['downloadId'], $params)]); + } + break; case 'close': $this->isClosed = true; $this->routeHandlers = []; @@ -1371,6 +1379,35 @@ public function waitForPopup(callable $action, array|WaitForPopupOptions $option return $popup; } + /** + * @param array|WaitForDownloadOptions $options + */ + public function waitForDownload(callable $action, array|WaitForDownloadOptions $options = []): DownloadInterface + { + $options = WaitForDownloadOptions::from($options)->toArray(); + $requestId = uniqid('download_', true); + + if (method_exists($this->transport, 'storePendingCallback')) { + $this->transport->storePendingCallback($requestId, $action); + } else { + $action(); + } + + $response = $this->transport->send([ + 'action' => 'page.waitForDownload', + 'pageId' => $this->pageId, + 'timeout' => $options['timeout'] ?? 30000, + 'requestId' => $requestId, + ]); + + $downloadId = $response['downloadId'] ?? null; + if (!is_string($downloadId)) { + throw new ProtocolErrorException('No download id returned from transport', 0); + } + + return new Download($this->transport, $this, $downloadId, $response); + } + /** * @param array|SetInputFilesOptions $options */ diff --git a/src/Page/PageEventHandler.php b/src/Page/PageEventHandler.php index 0ff77984..a6732066 100644 --- a/src/Page/PageEventHandler.php +++ b/src/Page/PageEventHandler.php @@ -56,4 +56,9 @@ public function onRoute(callable $handler): void { $this->on('route', $handler); } + + public function onDownload(callable $handler): void + { + $this->on('download', $handler); + } } diff --git a/src/Page/PageEventHandlerInterface.php b/src/Page/PageEventHandlerInterface.php index a01f8a0b..1fcfe155 100644 --- a/src/Page/PageEventHandlerInterface.php +++ b/src/Page/PageEventHandlerInterface.php @@ -37,4 +37,11 @@ public function onRequestFailed(callable $handler): void; * fulfill, abort, continue or fall back the route themselves. */ public function onRoute(callable $handler): void; + + /** + * Called with a DownloadInterface each time the page starts a download. + * Events reach PHP while it talks to the browser, so the handler runs + * during a later call on the page, not at the moment of the click. + */ + public function onDownload(callable $handler): void; } diff --git a/src/Page/PageInterface.php b/src/Page/PageInterface.php index 530979d8..ba1f6559 100644 --- a/src/Page/PageInterface.php +++ b/src/Page/PageInterface.php @@ -18,6 +18,7 @@ use Playwright\Browser\BrowserContextInterface; use Playwright\Clock\ClockInterface; use Playwright\Console\ConsoleMessage; +use Playwright\Download\DownloadInterface; use Playwright\Frame\FrameInterface; use Playwright\Frame\FrameLocatorInterface; use Playwright\Input\KeyboardInterface; @@ -44,6 +45,7 @@ use Playwright\Page\Options\SetInputFilesOptions; use Playwright\Page\Options\StyleTagOptions; use Playwright\Page\Options\TypeOptions; +use Playwright\Page\Options\WaitForDownloadOptions; use Playwright\Page\Options\WaitForFunctionOptions; use Playwright\Page\Options\WaitForLoadStateOptions; use Playwright\Page\Options\WaitForPopupOptions; @@ -398,6 +400,18 @@ public function waitForEvents(): void; */ public function waitForPopup(callable $action, array|WaitForPopupOptions $options = []): self; + /** + * Runs $action and returns the download it starts. + * + * The listener is armed before $action runs, so a download that starts + * right away is not missed. Throws a TimeoutException when no download + * starts within the timeout. + * + * @param callable(): mixed $action Starts the download, for example a click on a link + * @param array|WaitForDownloadOptions $options + */ + public function waitForDownload(callable $action, array|WaitForDownloadOptions $options = []): DownloadInterface; + /** * @param string|callable $url * @param array|WaitForResponseOptions $options diff --git a/tests/Fixtures/html/download.html b/tests/Fixtures/html/download.html new file mode 100644 index 00000000..e55bd098 --- /dev/null +++ b/tests/Fixtures/html/download.html @@ -0,0 +1,10 @@ + + +Downloads + + Report + Slow file + Inline file + + + diff --git a/tests/Fixtures/server.php b/tests/Fixtures/server.php index 463933b5..4330a5b6 100644 --- a/tests/Fixtures/server.php +++ b/tests/Fixtures/server.php @@ -62,6 +62,29 @@ return true; } +if ('/download/report.csv' === $uri) { + header('Content-Type: text/csv'); + header('Content-Disposition: attachment; filename="report.csv"'); + echo "id,name\n1,Ada\n"; + + return true; +} + +if ('/download/slow.bin' === $uri) { + header('Content-Type: application/octet-stream'); + header('Content-Disposition: attachment; filename="slow.bin"'); + header('Content-Length: 2048'); + while (ob_get_level() > 0) { + ob_end_flush(); + } + echo str_repeat('a', 1024); + flush(); + sleep(2); + echo str_repeat('b', 1024); + + return true; +} + // Default to index.html if root if ('/' === $uri) { $uri = '/index.html'; diff --git a/tests/Functional/Download/DownloadEventTest.php b/tests/Functional/Download/DownloadEventTest.php new file mode 100644 index 00000000..a91f5599 --- /dev/null +++ b/tests/Functional/Download/DownloadEventTest.php @@ -0,0 +1,75 @@ + $downloads */ + $downloads = []; + $this->page->events()->onDownload(static function (DownloadInterface $download) use (&$downloads): void { + $downloads[] = $download; + }); + $this->goto('/download.html'); + + $this->page->locator('#report')->click(); + $this->page->locator('#inline')->click(); + $this->waitUntil(static fn (): bool => 2 === count($downloads)); + + $this->assertSame(['report.csv', 'hello.txt'], array_map(static fn (DownloadInterface $download): string => $download->suggestedFilename(), $downloads)); + $this->assertSame($this->page, $downloads[0]->page()); + $path = $downloads[0]->path(); + $this->assertIsString($path); + $this->assertSame("id,name\n1,Ada\n", file_get_contents($path)); + } + + public function testTheListenerAndWaitForDownloadShareTheDownload(): void + { + $fromEvent = null; + $this->page->events()->onDownload(static function (DownloadInterface $download) use (&$fromEvent): void { + $fromEvent = $download; + }); + $this->goto('/download.html'); + + $download = $this->page->waitForDownload(fn () => $this->page->locator('#report')->click()); + $this->waitUntil(static fn (): bool => null !== $fromEvent); + + $this->assertInstanceOf(DownloadInterface::class, $fromEvent); + $this->assertSame($download->path(), $fromEvent->path()); + } + + /** + * Page events reach PHP while it exchanges messages with the bridge, so + * the test keeps the page busy until the listener has run. + */ + private function waitUntil(callable $condition): void + { + $deadline = microtime(true) + 5; + while (!$condition() && microtime(true) < $deadline) { + $this->page->evaluate('1'); + } + + $this->assertTrue($condition(), 'The download event did not reach PHP in time.'); + } +} diff --git a/tests/Functional/Download/WaitForDownloadTest.php b/tests/Functional/Download/WaitForDownloadTest.php new file mode 100644 index 00000000..a42a39ab --- /dev/null +++ b/tests/Functional/Download/WaitForDownloadTest.php @@ -0,0 +1,129 @@ +tempDir = sys_get_temp_dir().'/pw-php-wait-for-download-'.uniqid(); + mkdir($this->tempDir, 0777, true); + $this->goto('/download.html'); + } + + protected function tearDown(): void + { + foreach (glob($this->tempDir.'/*') ?: [] as $file) { + unlink($file); + } + rmdir($this->tempDir); + + parent::tearDown(); + } + + public function testReturnsTheDownloadStartedByTheAction(): void + { + $download = $this->page->waitForDownload(fn () => $this->page->locator('#report')->click()); + + $this->assertSame('report.csv', $download->suggestedFilename()); + $this->assertSame($this->getBaseUrl().'/download/report.csv', $download->url()); + $this->assertSame($this->page, $download->page()); + $this->assertNull($download->failure()); + + $path = $download->path(); + $this->assertIsString($path); + $this->assertSame("id,name\n1,Ada\n", file_get_contents($path)); + } + + public function testSavesAndStreamsTheDownloadedFile(): void + { + $download = $this->page->waitForDownload(fn () => $this->page->locator('#report')->click()); + + $target = $this->tempDir.'/saved.csv'; + $download->saveAs($target); + $this->assertSame("id,name\n1,Ada\n", file_get_contents($target)); + + $stream = $download->createReadStream(); + $this->assertIsResource($stream); + $this->assertSame("id,name\n1,Ada\n", stream_get_contents($stream)); + } + + public function testDeleteRemovesTheDownloadedFile(): void + { + $download = $this->page->waitForDownload(fn () => $this->page->locator('#report')->click()); + $path = $download->path(); + $this->assertIsString($path); + $this->assertFileExists($path); + + $download->delete(); + + $this->assertFileDoesNotExist($path); + } + + public function testTakesTheFilenameFromTheDownloadAttribute(): void + { + $download = $this->page->waitForDownload(fn () => $this->page->locator('#inline')->click()); + + $this->assertSame('hello.txt', $download->suggestedFilename()); + $path = $download->path(); + $this->assertIsString($path); + $this->assertSame('hello world', file_get_contents($path)); + } + + public function testACanceledDownloadReportsItsFailure(): void + { + $download = $this->page->waitForDownload(fn () => $this->page->locator('#slow')->click()); + + $download->cancel(); + + $this->assertSame('canceled', $download->failure()); + } + + public function testThrowsWhenNoDownloadStartsInTime(): void + { + $this->expectException(TimeoutException::class); + + $this->page->waitForDownload( + fn () => $this->page->locator('#nothing')->click(), + new WaitForDownloadOptions(timeout: 500), + ); + } + + public function testThePageStaysUsableAfterATimeout(): void + { + try { + $this->page->waitForDownload(fn () => null, ['timeout' => 300]); + $this->fail('Expected a TimeoutException'); + } catch (TimeoutException) { + } + + $download = $this->page->waitForDownload(fn () => $this->page->locator('#report')->click()); + + $this->assertSame('report.csv', $download->suggestedFilename()); + } +} diff --git a/tests/Unit/Download/DownloadTest.php b/tests/Unit/Download/DownloadTest.php index 0b90e9ac..9612f39a 100644 --- a/tests/Unit/Download/DownloadTest.php +++ b/tests/Unit/Download/DownloadTest.php @@ -56,12 +56,12 @@ public function testFailure(): void $transport = $this->createMock(TransportInterface::class); $transport->expects($this->once()) ->method('send') - ->willReturn(['error' => 'Download failed']); + ->willReturn(['failure' => 'canceled']); $page = $this->createMock(PageInterface::class); $download = new Download($transport, $page, 'dl-123', []); - $this->assertSame('Download failed', $download->failure()); + $this->assertSame('canceled', $download->failure()); } public function testFailureReturnsNull(): void diff --git a/tests/Unit/Page/Options/WaitForDownloadOptionsTest.php b/tests/Unit/Page/Options/WaitForDownloadOptionsTest.php new file mode 100644 index 00000000..8211d63b --- /dev/null +++ b/tests/Unit/Page/Options/WaitForDownloadOptionsTest.php @@ -0,0 +1,40 @@ +assertSame($options, WaitForDownloadOptions::from($options)); + } + + public function testItCreatesFromArray(): void + { + $this->assertSame(['timeout' => 5000.0], WaitForDownloadOptions::from(['timeout' => 5000])->toArray()); + } + + public function testItLeavesTheTimeoutOutWhenNotSet(): void + { + $this->assertSame([], WaitForDownloadOptions::from([])->toArray()); + } +} diff --git a/tests/Unit/Page/PageEventHandlerTest.php b/tests/Unit/Page/PageEventHandlerTest.php index 4d208d6e..3d854627 100644 --- a/tests/Unit/Page/PageEventHandlerTest.php +++ b/tests/Unit/Page/PageEventHandlerTest.php @@ -18,6 +18,7 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Playwright\Dialog\Dialog; +use Playwright\Download\Download; use Playwright\Network\Request; use Playwright\Network\Response; use Playwright\Page\PageEventHandler; @@ -149,6 +150,21 @@ public function testOnRequestFailedRegistersRequestFailedHandler(): void $this->assertSame($request, $receivedRequest); } + public function testOnDownloadRegistersDownloadHandler(): void + { + $handler = new PageEventHandler(); + $download = new Download($this->transport, $this->page, 'download_1'); + $received = null; + + $handler->onDownload(function (Download $d) use (&$received) { + $received = $d; + }); + + $handler->publicEmit('download', [$download]); + + $this->assertSame($download, $received); + } + public function testOnRouteRegistersRouteHandler(): void { $handler = new PageEventHandler(); diff --git a/tests/Unit/Page/PageTest.php b/tests/Unit/Page/PageTest.php index c14e6e02..0923497f 100644 --- a/tests/Unit/Page/PageTest.php +++ b/tests/Unit/Page/PageTest.php @@ -24,6 +24,7 @@ use Playwright\Clock\ClockInterface; use Playwright\Configuration\PlaywrightConfig; use Playwright\Console\ConsoleMessage; +use Playwright\Download\DownloadInterface; use Playwright\Exception\PlaywrightException; use Playwright\Exception\ProtocolErrorException; use Playwright\Exception\RuntimeException; @@ -39,6 +40,7 @@ use Playwright\Locator\Options\LocatorOptions; use Playwright\Page\Options\DragAndDropOptions; use Playwright\Page\Options\EmulateMediaOptions; +use Playwright\Page\Options\WaitForDownloadOptions; use Playwright\Page\Options\WaitForRequestOptions; use Playwright\Page\Page; use Playwright\Page\PageEventHandlerInterface; @@ -1205,6 +1207,90 @@ public function testWaitForPopupInvalidResponse(): void $page->waitForPopup($action); } + public function testWaitForDownloadRunsTheActionAndReturnsTheDownload(): void + { + $page = $this->createPage('page1'); + + $actionExecuted = false; + $action = function () use (&$actionExecuted) { + $actionExecuted = true; + }; + + $this->transport + ->expects($this->once()) + ->method('send') + ->with($this->callback(function ($payload) use (&$actionExecuted) { + $this->assertTrue($actionExecuted); + + return 'page.waitForDownload' === $payload['action'] + && 'page1' === $payload['pageId'] + && 30000 === $payload['timeout'] + && is_string($payload['requestId']); + })) + ->willReturn(['downloadId' => 'download_1', 'suggestedFilename' => 'report.csv', 'url' => 'https://example.test/report.csv']); + + $download = $page->waitForDownload($action); + + $this->assertSame('report.csv', $download->suggestedFilename()); + $this->assertSame('https://example.test/report.csv', $download->url()); + $this->assertSame($page, $download->page()); + } + + public function testWaitForDownloadWithCustomTimeout(): void + { + $page = $this->createPage('page1'); + + $this->transport + ->expects($this->once()) + ->method('send') + ->with($this->callback(static fn ($payload): bool => 5000.0 === $payload['timeout'])) + ->willReturn(['downloadId' => 'download_1']); + + $page->waitForDownload(static fn () => null, new WaitForDownloadOptions(timeout: 5000)); + } + + public function testWaitForDownloadRejectsAResponseWithoutDownloadId(): void + { + $page = $this->createPage('page1'); + + $this->transport + ->expects($this->once()) + ->method('send') + ->willReturn([]); + + $this->expectException(ProtocolErrorException::class); + $this->expectExceptionMessage('No download id returned from transport'); + + $page->waitForDownload(static fn () => null); + } + + public function testDownloadEventEmitsADownload(): void + { + $received = null; + $this->page->events()->onDownload(function (DownloadInterface $download) use (&$received) { + $received = $download; + }); + + $this->page->dispatchEvent('download', ['downloadId' => 'download_1', 'suggestedFilename' => 'report.csv', 'url' => 'https://example.test/report.csv']); + + $this->assertInstanceOf(DownloadInterface::class, $received); + $this->assertSame('report.csv', $received->suggestedFilename()); + $this->assertSame('https://example.test/report.csv', $received->url()); + $this->assertSame($this->page, $received->page()); + } + + public function testDownloadEventWithoutIdIsIgnored(): void + { + $called = false; + $this->page->events()->onDownload(function () use (&$called) { + $called = true; + }); + + $this->page->dispatchEvent('download', []); + + $this->assertFalse($called); + } + public function testRequestIsCached(): void { $transport = $this->createMock(TransportInterface::class);