Esempio n. 1
0
async def test_page_events_request_should_fire_for_navigation_requests(
    page: Page, server
):
    requests = []
    page.on("request", lambda r: requests.append(r))
    await page.goto(server.EMPTY_PAGE)
    assert len(requests) == 1
Esempio n. 2
0
async def test_should_emit_event(page: Page, server):
    await page.setContent("<input type=file>")
    fc_done: asyncio.Future = asyncio.Future()
    page.once("filechooser",
              lambda file_chooser: fc_done.set_result(file_chooser)),
    await page.click("input")
    file_chooser = await fc_done
    assert file_chooser
Esempio n. 3
0
async def test_should_return_the_same_file_chooser_when_there_are_many_watchdogs_simultaneously(
        page: Page, server):
    await page.setContent("<input type=file>")
    results = await asyncio.gather(
        page.waitForEvent("filechooser"),
        page.waitForEvent("filechooser"),
        page.evalOnSelector("input", "input => input.click()"),
    )
    assert results[0] == results[1]
async def test_page_events_request_should_report_requests_and_responses_handled_by_service_worker(
        page: Page, server):
    await page.goto(server.PREFIX + "/serviceworkers/fetchdummy/sw.html")
    await page.evaluate("() => window.activationPromise")
    [request, sw_response
     ] = await asyncio.gather(page.waitForEvent("request"),
                              page.evaluate('() => fetchDummy("foo")'))
    assert sw_response == "responseFromServiceWorker:foo"
    assert request.url == server.PREFIX + "/serviceworkers/fetchdummy/foo"
    response = await request.response
    assert response.url == server.PREFIX + "/serviceworkers/fetchdummy/foo"
    assert await response.text() == "responseFromServiceWorker:foo"
Esempio n. 5
0
async def test_should_accept_single_file(page: Page, server):
    await page.setContent(
        '<input type=file oninput="javascript:console.timeStamp()">')
    file_chooser = (await asyncio.gather(
        page.waitForEvent("filechooser"),
        page.click("input"),
    ))[0]
    assert file_chooser.page == page
    assert file_chooser.element
    await file_chooser.setFiles(FILE_TO_UPLOAD)
    assert await page.evalOnSelector("input",
                                     "input => input.files.length") == 1
    assert (await page.evalOnSelector(
        "input", "input => input.files[0].name") == "file-to-upload.txt")
Esempio n. 6
0
async def test_console_should_work(page: Page, server):
    messages: List[ConsoleMessage] = []
    page.once("console", lambda m: messages.append(m))
    await asyncio.gather(
        page.evaluate('() => console.log("hello", 5, {foo: "bar"})'),
        page.waitForEvent("console"),
    )
    assert len(messages) == 1
    message = messages[0]
    assert message.text == "hello 5 JSHandle@object"
    assert str(message) == "hello 5 JSHandle@object"
    assert message.type == "log"
    assert await message.args[0].jsonValue() == "hello"
    assert await message.args[1].jsonValue() == 5
    assert await message.args[2].jsonValue() == {"foo": "bar"}
async def test_should_report_downloads_with_acceptDownloads_false(page: Page, server):
    await page.setContent(
        f'<a href="{server.PREFIX}/downloadWithFilename">download</a>'
    )
    download = (await asyncio.gather(page.waitForEvent("download"), page.click("a")))[0]
    assert download.url == f"{server.PREFIX}/downloadWithFilename"
    assert download.suggestedFilename == "file.txt"
    error: Optional[PlaywrightError] = None
    try:
        await download.path()
    except PlaywrightError as exc:
        error = exc
    assert "acceptDownloads" in await download.failure()
    assert error
    assert "acceptDownloads: true" in error.message
async def test_request_headers_should_get_the_same_headers_as_the_server(
        page: Page, server):
    await page.goto(server.PREFIX + "/empty.html")
    server_request_headers_future: Future[Dict[str, str]] = asyncio.Future()

    def handle_something(request):
        normalized_headers = {
            key.decode().lower(): value[0].decode()
            for key, value in request.requestHeaders.getAllRawHeaders()
        }
        server_request_headers_future.set_result(normalized_headers)
        request.setHeader("Access-Control-Allow-Origin", "*")
        request.write(b"done")
        request.finish()

    server.set_route("/something", handle_something)

    requestPromise = asyncio.ensure_future(page.waitForEvent("request"))
    text = await page.evaluate(
        """async url => {
      const data = await fetch(url);
      return data.text();
    }""",
        server.CROSS_PROCESS_PREFIX + "/something",
    )
    request: Request = await requestPromise
    assert text == "done"
    server_headers = await server_request_headers_future
    assert request.headers == server_headers
Esempio n. 9
0
async def test_should_work_when_file_input_is_attached_to_DOM(
        page: Page, server):
    await page.setContent("<input type=file>")
    file_chooser = asyncio.create_task(page.waitForEvent("filechooser"))
    await asyncio.sleep(0)  # execute scheduled tasks, but don't await them
    await page.click("input")
    assert await file_chooser
async def test_page_route_should_be_abortable_with_custom_error_codes(
        page: Page, server, is_webkit, is_firefox):
    await page.route(
        "**/*",
        lambda route, _: asyncio.create_task(
            route.abort("internetdisconnected")),
    )
    failed_requests = []
    page.on("requestfailed", lambda request: failed_requests.append(request))
    with pytest.raises(Error):
        await page.goto(server.EMPTY_PAGE)
    assert len(failed_requests) == 1
    failed_request = failed_requests[0]
    if is_webkit:
        assert failed_request.failure == "Request intercepted"
    elif is_firefox:
        assert failed_request.failure == "NS_ERROR_OFFLINE"
    else:
        assert failed_request.failure == "net::ERR_INTERNET_DISCONNECTED"
Esempio n. 11
0
async def test_should_be_able_to_read_selected_file(page: Page, server):
    page.once(
        "filechooser",
        lambda file_chooser: asyncio.create_task(
            file_chooser.setFiles(FILE_TO_UPLOAD)),
    )
    await page.setContent("<input type=file>")
    content = await page.evalOnSelector(
        "input",
        """async picker => {
            picker.click();
            await new Promise(x => picker.oninput = x);
            const reader = new FileReader();
            const promise = new Promise(fulfill => reader.onload = fulfill);
            reader.readAsText(picker.files[0]);
            return promise.then(() => reader.result);
        }""",
    )
    assert content == "contents of the file\n"
async def test_workers_should_emit_created_and_destroyed_events(page: Page):
    worker_createdpromise = asyncio.ensure_future(page.waitForEvent("worker"))
    worker_obj = await page.evaluateHandle(
        "() => new Worker(URL.createObjectURL(new Blob(['1'], {type: 'application/javascript'})))"
    )
    worker = await worker_createdpromise
    worker_this_obj = await worker.evaluateHandle("() => this")
    worker_destroyed_promise: Future[Worker] = asyncio.Future()
    worker.once("close", lambda w: worker_destroyed_promise.set_result(w))
    await page.evaluate("workerObj => workerObj.terminate()", worker_obj)
    assert await worker_destroyed_promise == worker
    with pytest.raises(Error) as exc:
        await worker_this_obj.getProperty("self")
    assert "Most likely the worker has been closed." in exc.value.message
Esempio n. 13
0
def create_remote_object(parent: ChannelOwner, type: str, guid: str,
                         initializer: Dict) -> Any:
    if type == "BindingCall":
        return BindingCall(parent, type, guid, initializer)
    if type == "Browser":
        return Browser(cast(BrowserType, parent), type, guid, initializer)
    if type == "BrowserType":
        return BrowserType(parent, type, guid, initializer)
    if type == "BrowserContext":
        browser_name: str = ""
        if isinstance(parent, Browser):
            browser_name = parent._browser_type.name
        if isinstance(parent, BrowserType):
            browser_name = parent.name
        if browser_name == "chromium":
            return ChromiumBrowserContext(parent, type, guid, initializer)
        return BrowserContext(parent, type, guid, initializer)
    if type == "CDPSession":
        return CDPSession(parent, type, guid, initializer)
    if type == "ConsoleMessage":
        return ConsoleMessage(parent, type, guid, initializer)
    if type == "Dialog":
        return Dialog(parent, type, guid, initializer)
    if type == "Download":
        return Download(parent, type, guid, initializer)
    if type == "ElementHandle":
        return ElementHandle(parent, type, guid, initializer)
    if type == "Frame":
        return Frame(parent, type, guid, initializer)
    if type == "JSHandle":
        return JSHandle(parent, type, guid, initializer)
    if type == "Page":
        return Page(parent, type, guid, initializer)
    if type == "Playwright":
        return Playwright(parent, type, guid, initializer)
    if type == "Request":
        return Request(parent, type, guid, initializer)
    if type == "Response":
        return Response(parent, type, guid, initializer)
    if type == "Route":
        return Route(parent, type, guid, initializer)
    if type == "WebSocket":
        return WebSocket(parent, type, guid, initializer)
    if type == "Worker":
        return Worker(parent, type, guid, initializer)
    if type == "Selectors":
        return Selectors(parent, type, guid, initializer)
    return DummyObject(parent, type, guid, initializer)
Esempio n. 14
0
async def test_should_be_able_to_reset_selected_files_with_empty_file_list(
        page: Page, server):
    await page.setContent("<input type=file>")
    page.once(
        "filechooser",
        lambda file_chooser: asyncio.create_task(
            file_chooser.setFiles(FILE_TO_UPLOAD)),
    )
    file_length_1 = (await asyncio.gather(
        page.waitForEvent("filechooser"),
        page.evalOnSelector(
            "input",
            """async picker => {
                    picker.click();
                    await new Promise(x => picker.oninput = x);
                    return picker.files.length;
                }""",
        ),
    ))[1]
    assert file_length_1 == 1

    page.once(
        "filechooser",
        lambda file_chooser: asyncio.create_task(file_chooser.setFiles([])),
    )
    file_length_2 = (await asyncio.gather(
        page.waitForEvent("filechooser"),
        page.evalOnSelector(
            "input",
            """async picker => {
                    picker.click()
                    await new Promise(x => picker.oninput = x)
                    return picker.files.length
                }""",
        ),
    ))[1]
    assert file_length_2 == 0
Esempio n. 15
0
def create_remote_object(parent: ChannelOwner, type: str, guid: str,
                         initializer: Dict) -> Any:
    if type == "BindingCall":
        return BindingCall(parent, type, guid, initializer)
    if type == "Browser":
        return Browser(parent, type, guid, initializer)
    if type == "BrowserServer":
        return BrowserServer(parent, type, guid, initializer)
    if type == "BrowserType":
        return BrowserType(parent, type, guid, initializer)
    if type == "BrowserContext":
        return BrowserContext(parent, type, guid, initializer)
    if type == "ConsoleMessage":
        return ConsoleMessage(parent, type, guid, initializer)
    if type == "Dialog":
        return Dialog(parent, type, guid, initializer)
    if type == "Download":
        return Download(parent, type, guid, initializer)
    if type == "ElementHandle":
        return ElementHandle(parent, type, guid, initializer)
    if type == "Frame":
        return Frame(parent, type, guid, initializer)
    if type == "JSHandle":
        return JSHandle(parent, type, guid, initializer)
    if type == "Page":
        return Page(parent, type, guid, initializer)
    if type == "Playwright":
        return Playwright(parent, type, guid, initializer)
    if type == "Request":
        return Request(parent, type, guid, initializer)
    if type == "Response":
        return Response(parent, type, guid, initializer)
    if type == "Route":
        return Route(parent, type, guid, initializer)
    if type == "Worker":
        return Worker(parent, type, guid, initializer)
    if type == "Selectors":
        return Selectors(parent, type, guid, initializer)
    return DummyObject(parent, type, guid, initializer)
Esempio n. 16
0
def create_remote_object(scope: ConnectionScope, type: str, guid: str,
                         initializer: Dict) -> Any:
    if type == "bindingCall":
        return BindingCall(scope, guid, initializer)
    if type == "browser":
        return Browser(scope, guid, initializer)
    if type == "browserServer":
        return BrowserServer(scope, guid, initializer)
    if type == "browserType":
        return BrowserType(scope, guid, initializer)
    if type == "context":
        return BrowserContext(scope, guid, initializer)
    if type == "consoleMessage":
        return ConsoleMessage(scope, guid, initializer)
    if type == "dialog":
        return Dialog(scope, guid, initializer)
    if type == "download":
        return Download(scope, guid, initializer)
    if type == "elementHandle":
        return ElementHandle(scope, guid, initializer)
    if type == "frame":
        return Frame(scope, guid, initializer)
    if type == "jsHandle":
        return JSHandle(scope, guid, initializer)
    if type == "page":
        return Page(scope, guid, initializer)
    if type == "playwright":
        return Playwright(scope, guid, initializer)
    if type == "request":
        return Request(scope, guid, initializer)
    if type == "response":
        return Response(scope, guid, initializer)
    if type == "route":
        return Route(scope, guid, initializer)
    if type == "worker":
        return Worker(scope, guid, initializer)
async def test_should_work_when_file_input_is_attached_to_DOM(
        page: Page, server):
    await page.setContent("<input type=file>")
    file_chooser = asyncio.ensure_future(page.waitForEvent("filechooser"))
    await page.click("input")
    assert await file_chooser
Esempio n. 18
0
 def _on_page(self, page: Page) -> None:
     page._set_browser_context(self)
     self._pages.append(page)
     self.emit(BrowserContext.Events.Page, page)
Esempio n. 19
0
def test_should_be_able_to_save_pdf_file(page: Page, server, tmpdir: Path):
    output_file = tmpdir / "foo.png"
    page.pdf(path=str(output_file))
    assert os.path.getsize(output_file) > 0
Esempio n. 20
0
 async def verify_viewport(self, page: Page, width: int, height: int):
     assert cast(Viewport, page.viewportSize())["width"] == width
     assert cast(Viewport, page.viewportSize())["height"] == height
     assert await page.evaluate("window.innerWidth") == width
     assert await page.evaluate("window.innerHeight") == height
Esempio n. 21
0
def test_should_be_able_capture_pdf_without_path(page: Page):
    buffer = page.pdf()
    assert buffer