def test_should_work_for_redirect(page: Page, server: Server) -> None:
    server.set_redirect("/foo.html", "/empty.html")
    responses = []
    page.on("response", lambda response: responses.append(response))
    page.goto(server.PREFIX + "/foo.html")
    for r in responses:
        r.finished()

    assert len(responses) == 2
    assert responses[0].url == server.PREFIX + "/foo.html"
    assert responses[1].url == server.PREFIX + "/empty.html"

    timing1 = responses[0].request.timing
    verify_connections_timing_consistency(timing1)
    assert timing1["requestStart"] >= timing1["connectEnd"]
    assert timing1["responseStart"] > timing1["requestStart"]
    assert timing1["responseEnd"] >= timing1["responseStart"]
    assert timing1["responseEnd"] < 10000

    timing2 = responses[1].request.timing
    verify_connections_timing_consistency(timing2)
    assert timing2["requestStart"] >= 0
    assert timing2["responseStart"] > timing2["requestStart"]
    assert timing2["responseEnd"] >= timing2["responseStart"]
    assert timing2["responseEnd"] < 10000
async def test_should_not_allow_getting_the_path(
    browser_type: BrowserType, launch_server, server: Server
):
    def handle_download(request):
        request.setHeader("Content-Type", "application/octet-stream")
        request.setHeader("Content-Disposition", "attachment")
        request.write(b"Hello world")
        request.finish()

    server.set_route("/download", handle_download)

    remote_server = launch_server()
    browser = await browser_type.connect(remote_server.ws_endpoint)
    page = await browser.new_page(accept_downloads=True)
    await page.set_content(f'<a href="{server.PREFIX}/download">download</a>')
    async with page.expect_download() as download_info:
        await page.click("a")
    download = await download_info.value
    with pytest.raises(Error) as exc:
        await download.path()
    assert (
        exc.value.message
        == "Path is not available when using browser_type.connect(). Use save_as() to save a local copy."
    )
    remote_server.kill()
Example #3
0
def test_sync_network_events(page: Page, server: Server) -> None:
    server.set_route(
        "/hello-world",
        lambda request: (
            request.setHeader("Content-Type", "text/plain"),
            request.write(b"Hello world"),
            request.finish(),
        ),
    )
    page.goto(server.EMPTY_PAGE)
    messages = []
    page.on(
        "request",
        lambda request: messages.append(f">>{request.method}{request.url}"))
    page.on(
        "response",
        lambda response: messages.append(f"<<{response.status}{response.url}"),
    )
    response = page.evaluate(
        """async ()=> (await fetch("/hello-world")).text()""")
    assert response == "Hello world"
    assert messages == [
        f">>GET{server.PREFIX}/hello-world",
        f"<<200{server.PREFIX}/hello-world",
    ]
Example #4
0
async def test_should_round_trip_har_with_post_data(browser: Browser,
                                                    server: Server,
                                                    assetdir: Path,
                                                    tmpdir: Path) -> None:
    server.set_route("/echo", lambda req:
                     (req.write(req.post_body), req.finish()))
    fetch_function = """
        async (body) => {
            const response = await fetch('/echo', { method: 'POST', body });
            return await response.text();
        };
    """
    har_path = tmpdir / "har.zip"
    context_1 = await browser.new_context(record_har_mode="minimal",
                                          record_har_path=har_path)
    page_1 = await context_1.new_page()
    await page_1.goto(server.EMPTY_PAGE)

    assert await page_1.evaluate(fetch_function, "1") == "1"
    assert await page_1.evaluate(fetch_function, "2") == "2"
    assert await page_1.evaluate(fetch_function, "3") == "3"
    await context_1.close()

    context_2 = await browser.new_context()
    await context_2.route_from_har(har=har_path, not_found="abort")
    page_2 = await context_2.new_page()
    await page_2.goto(server.EMPTY_PAGE)
    assert await page_2.evaluate(fetch_function, "1") == "1"
    assert await page_2.evaluate(fetch_function, "2") == "2"
    assert await page_2.evaluate(fetch_function, "3") == "3"
    with pytest.raises(Exception):
        await page_2.evaluate(fetch_function, "4")
Example #5
0
async def test_should_return_error_with_wrong_credentials(
        playwright: Playwright, server: Server):
    server.set_auth("/empty.html", "user", "pass")
    request = await playwright.request.new_context(http_credentials={
        "username": "******",
        "password": "******"
    })
    response = await request.get(server.EMPTY_PAGE)
    assert response.status == 401
    assert response.ok is False
Example #6
0
def test_should_propagate_extra_http_headers_with_redirects(
        playwright: Playwright, server: Server) -> None:
    server.set_redirect("/a/redirect1", "/b/c/redirect2")
    server.set_redirect("/b/c/redirect2", "/simple.json")
    request = playwright.request.new_context(
        extra_http_headers={"My-Secret": "Value"})
    with server.expect_request("/a/redirect1") as server_req1:
        with server.expect_request("/b/c/redirect2") as server_req2:
            with server.expect_request("/simple.json") as server_req3:
                request.get(f"{server.PREFIX}/a/redirect1"),
    assert server_req1.value.getHeader("my-secret") == "Value"
    assert server_req2.value.getHeader("my-secret") == "Value"
    assert server_req3.value.getHeader("my-secret") == "Value"
Example #7
0
async def test_should_delete_header_with_undefined_value(
        page: Page, context: BrowserContext, server: Server) -> None:
    await page.goto(server.EMPTY_PAGE)
    server.set_route(
        "/something",
        lambda r: (
            r.setHeader("Acces-Control-Allow-Origin", "*"),
            r.write(b"done"),
            r.finish(),
        ),
    )

    intercepted_request = []

    async def capture_and_continue(route: Route, request: Request):
        intercepted_request.append(request)
        await route.continue_()

    await context.route("**/*", capture_and_continue)

    async def delete_foo_header(route: Route, request: Request):
        headers = await request.all_headers()
        await route.fallback(headers={**headers, "foo": None})

    await context.route(server.PREFIX + "/something", delete_foo_header)

    [server_req, text] = await asyncio.gather(
        server.wait_for_request("/something"),
        page.evaluate(
            """
            async url => {
                const data = await fetch(url, {
                    headers: {
                    foo: 'a',
                    bar: 'b',
                    }
                });
                return data.text();
                }
            """,
            server.PREFIX + "/something",
        ),
    )

    assert text == "done"
    assert not intercepted_request[0].headers.get("foo")
    assert intercepted_request[0].headers.get("bar") == "b"
    assert not server_req.getHeader("foo")
    assert server_req.getHeader("bar") == "b"
Example #8
0
async def test_should_propagate_extra_http_headers_with_redirects(
        playwright: Playwright, server: Server):
    server.set_redirect("/a/redirect1", "/b/c/redirect2")
    server.set_redirect("/b/c/redirect2", "/simple.json")
    request = await playwright.request.new_context(
        extra_http_headers={"My-Secret": "Value"})
    [req1, req2, req3, _] = await asyncio.gather(
        server.wait_for_request("/a/redirect1"),
        server.wait_for_request("/b/c/redirect2"),
        server.wait_for_request("/simple.json"),
        request.get(f"{server.PREFIX}/a/redirect1"),
    )
    assert req1.getHeader("my-secret") == "Value"
    assert req2.getHeader("my-secret") == "Value"
    assert req3.getHeader("my-secret") == "Value"
Example #9
0
async def test_should_support_multipart_form_data(context: BrowserContext,
                                                  server: Server):
    file = {
        "name": "f.js",
        "mimeType": "text/javascript",
        "buffer": b"var x = 10;\r\n;console.log(x);",
    }
    [request, response] = await asyncio.gather(
        server.wait_for_request("/empty.html"),
        context.request.post(
            server.PREFIX + "/empty.html",
            multipart={
                "firstName": "John",
                "lastName": "Doe",
                "file": file,
            },
        ),
    )
    assert request.method == b"POST"
    assert request.getHeader("Content-Type").startswith(
        "multipart/form-data; ")
    assert request.getHeader("Content-Length") == str(len(request.post_body))
    assert request.args[b"firstName"] == [b"John"]
    assert request.args[b"lastName"] == [b"Doe"]
    assert request.args[b"file"][0] == file["buffer"]
Example #10
0
def test_should_support_multipart_form_data(context: BrowserContext,
                                            server: Server) -> None:
    file: FilePayload = {
        "name": "f.js",
        "mimeType": "text/javascript",
        "buffer": b"var x = 10;\r\n;console.log(x);",
    }
    with server.expect_request("/empty.html") as server_req:
        context.request.post(
            server.PREFIX + "/empty.html",
            multipart={
                "firstName": "John",
                "lastName": "Doe",
                "file": file,
            },
        )
    assert server_req.value.method == b"POST"
    content_type = server_req.value.getHeader("Content-Type")
    assert content_type
    assert content_type.startswith("multipart/form-data; ")
    assert server_req.value.getHeader("Content-Length") == str(
        len(server_req.value.post_body)  # type: ignore
    )
    assert server_req.value.args[b"firstName"] == [b"John"]
    assert server_req.value.args[b"lastName"] == [b"Doe"]
    assert server_req.value.args[b"file"][0] == file["buffer"]
Example #11
0
async def test_should_amend_binary_post_data(page: Page,
                                             context: BrowserContext,
                                             server: Server):
    await page.goto(server.EMPTY_PAGE)
    post_data_buffer = []
    await context.route(
        "**/*",
        lambda route: (
            post_data_buffer.append(route.request.post_data),
            asyncio.create_task(route.continue_()),
        ),
    )
    await context.route(
        "**/*",
        lambda route: asyncio.create_task(
            route.fallback(post_data=b"\x00\x01\x02\x03\x04")),
    )

    [server_request, result] = await asyncio.gather(
        server.wait_for_request("/sleep.zzz"),
        page.evaluate(
            "fetch('/sleep.zzz', { method: 'POST', body: 'birdy' })"),
    )
    # FIXME: should this be bytes?
    assert post_data_buffer == ["\x00\x01\x02\x03\x04"]
    assert server_request.method == b"POST"
    assert server_request.post_body == b"\x00\x01\x02\x03\x04"
Example #12
0
async def test_should_support_global_http_credentials_option(
        playwright: Playwright, server: Server):
    server.set_auth("/empty.html", "user", "pass")
    request1 = await playwright.request.new_context()
    response1 = await request1.get(server.EMPTY_PAGE)
    assert response1.status == 401
    await response1.dispose()

    request2 = await playwright.request.new_context(http_credentials={
        "username": "******",
        "password": "******"
    })
    response2 = await request2.get(server.EMPTY_PAGE)
    assert response2.status == 200
    assert response2.ok is True
    await response2.dispose()
Example #13
0
async def test_should_override_request_url(page: Page, context: BrowserContext,
                                           server: Server) -> None:
    url = []
    await context.route(
        "**/global-var.html",
        lambda route: (
            url.append(route.request.url),
            asyncio.create_task(route.continue_()),
        ),
    )
    await context.route(
        "**/foo",
        lambda route: asyncio.create_task(
            route.fallback(url=server.PREFIX + "/global-var.html")),
    )

    [server_request, response, _] = await asyncio.gather(
        server.wait_for_request("/global-var.html"),
        page.wait_for_event("response"),
        page.goto(server.PREFIX + "/foo"),
    )

    assert url == [server.PREFIX + "/global-var.html"]
    assert response.url == server.PREFIX + "/foo"
    assert await page.evaluate("() => window['globalVar']") == 123
    assert server_request.uri == b"/global-var.html"
    assert server_request.method == b"GET"
async def test_should_report_request_headers_array(page: Page, server: Server,
                                                   is_win: bool,
                                                   browser_name: str) -> None:
    if is_win and browser_name == "webkit":
        pytest.skip(
            "libcurl does not support non-set-cookie multivalue headers")
    expected_headers = []

    def handle(request: http.Request):
        for name, values in request.requestHeaders.getAllRawHeaders():
            for value in values:
                expected_headers.append({
                    "name": name.decode().lower(),
                    "value": value.decode()
                })
        request.finish()

    server.set_route("/headers", handle)
    await page.goto(server.EMPTY_PAGE)
    async with page.expect_request("*/**") as request_info:
        await page.evaluate("""() => fetch('/headers', {
            headers: [
                ['header-a', 'value-a'],
                ['header-b', 'value-b'],
                ['header-a', 'value-a-1'],
                ['header-a', 'value-a-2'],
            ]
            })
        """)
    request = await request_info.value
    sorted_pw_request_headers = sorted(
        list(
            map(
                lambda header: {
                    "name": header["name"].lower(),
                    "value": header["value"],
                },
                await request.headers_array(),
            )),
        key=lambda header: header["name"],
    )
    sorted_expected_headers = sorted(expected_headers,
                                     key=lambda header: header["name"])
    assert sorted_pw_request_headers == sorted_expected_headers
    assert await request.header_value("Header-A"
                                      ) == "value-a, value-a-1, value-a-2"
    assert await request.header_value("not-there") is None
async def test_should_fulfill_with_any_response(page: Page, server: Server):
    def server_handler(request: http.Request):
        request.setHeader("foo", "bar")
        request.write("Woo-hoo".encode())
        request.finish()

    server.set_route("/sample", server_handler)
    sample_response = await page.request.get(server.PREFIX + "/sample")
    await page.route(
        "**/*",
        lambda route: route.fulfill(
            response=sample_response, status=201, content_type="text/plain"),
    )
    response = await page.goto(server.EMPTY_PAGE)
    assert response.status == 201
    assert await response.text() == "Woo-hoo"
    assert response.headers["foo"] == "bar"
Example #16
0
def test_should_use_playwright_as_a_user_agent(playwright: Playwright,
                                               server: Server) -> None:
    request = playwright.request.new_context()
    with server.expect_request("/empty.html") as server_req:
        request.get(server.EMPTY_PAGE),
    assert str(
        server_req.value.getHeader("User-Agent")).startswith("Playwright/")
    request.dispose()
Example #17
0
def test_should_add_default_headers(context: BrowserContext, page: Page,
                                    server: Server) -> None:
    with server.expect_request("/empty.html") as server_req:
        context.request.get(server.EMPTY_PAGE)
    assert server_req.value.getHeader("Accept") == "*/*"
    assert server_req.value.getHeader("Accept-Encoding") == "gzip,deflate,br"
    assert server_req.value.getHeader("User-Agent") == page.evaluate(
        "() => navigator.userAgent")
Example #18
0
    def test_functionality(self):
        db_generator = TestingDBGenerator()
        common_config = {}
        config = {"repo_uri": "127.0.0.1:8080"}

        packages = [Package("app-test1", "test", "1"), Package("app-test1", "test", "2"),
                    Package("app-test1", "test1", "1"), Package("app-test2", "test2", "1")]
        ebuild_data = {"test1": "test1", "test2": "test2"}

        orig_tempdir = TemporaryDirectory()
        with open(os.path.join(orig_tempdir.name, "repo.data"), "w") as f:
            for key, value in ebuild_data.items():
                f.write(key + " " + value + "\n")
            f.write("packages\n")
            for package in packages:
                f.write(package.category + " " +  package.name + " " + package.version + "\n")

        srv = Server(orig_tempdir.name)
        srv.start()

        pkg_db = db_generator(self.tempdir.name, "test_repo",
                              common_config = common_config, config = config)

        srv.shutdown()
        srv.join()

        self.assertEqual(set(pkg_db.list_categories()), set(["app-test1", "app-test2"]))
        self.assertTrue(pkg_db.in_category("app-test1", "test"))
        self.assertFalse(pkg_db.in_category("app-test2", "test"))
        self.assertRaises(InvalidKeyError, pkg_db.in_category, "app-test3", "test")
        self.assertEqual(set(pkg_db.list_package_names("app-test1")), set(['test', 'test1']))
        self.assertEqual(set(pkg_db.list_catpkg_names()),set(['app-test1/test', 'app-test1/test1', 'app-test2/test2']))
        self.assertRaises(InvalidKeyError, pkg_db.list_package_versions, "invalid", "test")
        self.assertRaises(InvalidKeyError, pkg_db.list_package_versions, "app-test1", "invalid")
        self.assertEqual(set(pkg_db.list_package_versions("app-test1", "test")), set(['1', '2']))
        self.assertEqual(set(pkg_db.list_all_packages()), set(packages))
        self.assertEqual(pkg_db.get_package_description(packages[0]), ebuild_data)
        self.assertRaises(KeyError, pkg_db.get_package_description, Package("invalid", "invalid", "1"))
        self.assertEqual(pkg_db.get_max_version("app-test1", "test"), "2")
        self.assertEqual(pkg_db.get_max_version("app-test1", "test1"), "1")
        self.assertRaises(InvalidKeyError, pkg_db.get_max_version, "invalid", "invalid")
        pkg_set = set(packages)
        for package, data in pkg_db:
            self.assertTrue(package in pkg_set)
            self.assertEqual(data, ebuild_data)
            pkg_set.remove(package)
        self.assertTrue(not pkg_set)

        orig = "test"
        converted = "works"
        internal = "int"
        configs = [{}, {"converters": {orig:converted}, "external": {orig:converted}, "values": [orig, converted]}]

        self.assertEqual(db_generator.convert(configs, "converters", orig), converted)
        self.assertNotEqual(db_generator.convert(configs, "converters", "invalid"), converted)
        self.assertEqual(db_generator.convert_dependency(configs, orig), ("external", converted))
        self.assertEqual(db_generator.convert_dependency(configs, orig, external = False), None)
        self.assertEqual(db_generator.convert_dependency(configs, internal), ("internal", internal))
        self.assertTrue(db_generator.in_config(configs, "values", orig))
        self.assertFalse(db_generator.in_config(configs, "values", "invalid"))
Example #19
0
def test_should_support_query_params(context: BrowserContext, server: Server,
                                     method: str) -> None:
    expected_params = {"p1": "v1", "парам2": "знач2"}
    with server.expect_request("/empty.html") as server_req:
        getattr(context.request, method)(server.EMPTY_PAGE + "?p1=foo",
                                         params=expected_params)
    assert server_req.value.args["p1".encode()][0].decode() == "v1"
    assert len(server_req.value.args["p1".encode()]) == 1
    assert server_req.value.args["парам2".encode()][0].decode() == "знач2"
Example #20
0
async def test_should_use_playwright_as_a_user_agent(playwright: Playwright,
                                                     server: Server):
    request = await playwright.request.new_context()
    [server_req, _] = await asyncio.gather(
        server.wait_for_request("/empty.html"),
        request.get(server.EMPTY_PAGE),
    )
    assert str(server_req.getHeader("User-Agent")).startswith("Playwright/")
    await request.dispose()
Example #21
0
async def test_should_add_default_headers(context: BrowserContext, page: Page,
                                          server: Server):
    [request, response] = await asyncio.gather(
        server.wait_for_request("/empty.html"),
        context.request.get(server.EMPTY_PAGE),
    )
    assert request.getHeader("Accept") == "*/*"
    assert request.getHeader("Accept-Encoding") == "gzip,deflate,br"
    assert request.getHeader("User-Agent") == await page.evaluate(
        "() => navigator.userAgent")
async def test_should_report_response_headers_array(page: Page, server: Server,
                                                    is_win,
                                                    browser_name) -> None:
    if is_win and browser_name == "webkit":
        pytest.skip(
            "libcurl does not support non-set-cookie multivalue headers")
    expected_headers = {
        "header-a": ["value-a", "value-a-1", "value-a-2"],
        "header-b": ["value-b"],
        "set-cookie": ["a=b", "c=d"],
    }

    def handle(request: http.Request):
        for key in expected_headers:
            for value in expected_headers[key]:
                request.responseHeaders.addRawHeader(key, value)
        request.finish()

    server.set_route("/headers", handle)
    await page.goto(server.EMPTY_PAGE)
    async with page.expect_response("*/**") as response_info:
        await page.evaluate("""() => fetch('/headers')
        """)
    response = await response_info.value
    actual_headers = {}
    for header in await response.headers_array():
        name = header["name"].lower()
        value = header["value"]
        if not actual_headers.get(name):
            actual_headers[name] = []
        actual_headers[name].append(value)

    for key in ["Keep-Alive", "Connection", "Date", "Transfer-Encoding"]:
        if key in actual_headers:
            actual_headers.pop(key)
        if key.lower() in actual_headers:
            actual_headers.pop(key.lower())
    assert actual_headers == expected_headers
    assert await response.header_value("not-there") is None
    assert await response.header_value("set-cookie") == "a=b\nc=d"
    assert await response.header_value("header-a"
                                       ) == "value-a, value-a-1, value-a-2"
    assert await response.header_values("set-cookie") == ["a=b", "c=d"]
Example #23
0
async def test_should_contain_default_user_agent(playwright: Playwright,
                                                 server: Server):
    request = await playwright.request.new_context()
    [request, _] = await asyncio.gather(
        server.wait_for_request("/empty.html"),
        request.get(server.EMPTY_PAGE),
    )
    user_agent = request.getHeader("user-agent")
    assert "python" in user_agent
    assert f"{sys.version_info.major}.{sys.version_info.minor}" in user_agent
Example #24
0
def test_should_support_global_user_agent_option(playwright: Playwright,
                                                 server: Server) -> None:
    request = playwright.request.new_context(user_agent="My Agent")
    response = request.get(server.PREFIX + "/empty.html")
    with server.expect_request("/empty.html") as server_req:
        request.get(server.EMPTY_PAGE)
    assert response.ok is True
    assert response.url == server.EMPTY_PAGE

    assert server_req.value.getHeader("user-agent") == "My Agent"
Example #25
0
async def test_should_support_global_user_agent_option(playwright: Playwright,
                                                       server: Server):
    request = await playwright.request.new_context(user_agent="My Agent")
    response = await request.get(server.PREFIX + "/empty.html")
    [request, _] = await asyncio.gather(
        server.wait_for_request("/empty.html"),
        request.get(server.EMPTY_PAGE),
    )
    assert response.ok is True
    assert response.url == server.EMPTY_PAGE
    assert request.getHeader("user-agent") == "My Agent"
Example #26
0
async def test_should_support_query_params(context: BrowserContext,
                                           server: Server, method: str):
    expected_params = {"p1": "v1", "парам2": "знач2"}
    [server_req, _] = await asyncio.gather(
        server.wait_for_request("/empty.html"),
        getattr(context.request, method)(server.EMPTY_PAGE + "?p1=foo",
                                         params=expected_params),
    )
    assert server_req.args["p1".encode()][0].decode() == "v1"
    assert len(server_req.args["p1".encode()]) == 1
    assert server_req.args["парам2".encode()][0].decode() == "знач2"
async def test_frame_wait_for_nav_should_fail_when_frame_detaches(page, server: Server):
    await page.goto(server.PREFIX + "/frames/one-frame.html")
    frame = page.frames[1]
    server.set_route("/empty.html", lambda _: None)
    with pytest.raises(Error) as exc_info:
        async with frame.expect_navigation():

            async def after_it():
                await server.wait_for_request("/empty.html")
                await page.eval_on_selector(
                    "iframe", "frame => setTimeout(() => frame.remove(), 0)"
                )

            await asyncio.gather(
                page.eval_on_selector(
                    "iframe",
                    "frame => frame.contentWindow.location.href = '/empty.html'",
                ),
                after_it(),
            )
    assert "frame was detached" in exc_info.value.message
async def test_should_override_with_defaults_when_intercepted_response_not_provided(
        page: Page, server: Server, browser_name: str):
    def server_handler(request: http.Request):
        request.setHeader("foo", "bar")
        request.write("my content".encode())
        request.finish()

    server.set_route("/empty.html", server_handler)

    async def handle(route: Route):
        await page.request.fetch(route.request)
        await route.fulfill(status=201)

    await page.route("**/*", handle)
    response = await page.goto(server.EMPTY_PAGE)
    assert response.status == 201
    assert await response.text() == ""
    if browser_name == "webkit":
        assert response.headers == {"content-type": "text/plain"}
    else:
        assert response.headers == {}
async def test_should_upload_large_file(
    browser_type: BrowserType,
    launch_server: Callable[[], RemoteServer],
    playwright: Playwright,
    server: Server,
    tmp_path,
):
    remote = launch_server()

    browser = await browser_type.connect(remote.ws_endpoint)
    context = await browser.new_context()
    page = await context.new_page()

    await page.goto(server.PREFIX + "/input/fileupload.html")
    large_file_path = tmp_path / "200MB.zip"
    data = b"A" * 1024
    with large_file_path.open("wb") as f:
        for i in range(0, 200 * 1024 * 1024, len(data)):
            f.write(data)
    input = page.locator('input[type="file"]')
    events = await input.evaluate_handle(
        """
        e => {
            const events = [];
            e.addEventListener('input', () => events.push('input'));
            e.addEventListener('change', () => events.push('change'));
            return events;
        }
    """
    )

    await input.set_input_files(large_file_path)
    assert await input.evaluate("e => e.files[0].name") == "200MB.zip"
    assert await events.evaluate("e => e") == ["input", "change"]

    [request, _] = await asyncio.gather(
        server.wait_for_request("/upload"),
        page.click("input[type=submit]"),
    )

    contents = request.args[b"file1"][0]
    assert len(contents) == 200 * 1024 * 1024
    assert contents[:1024] == data
    # flake8: noqa: E203
    assert contents[len(contents) - 1024 :] == data
    match = re.search(
        rb'^.*Content-Disposition: form-data; name="(?P<name>.*)"; filename="(?P<filename>.*)".*$',
        request.post_body,
        re.MULTILINE,
    )
    assert match.group("name") == b"file1"
    assert match.group("filename") == b"200MB.zip"
Example #30
0
def test_sync_download(browser: Browser, server: Server) -> None:
    server.set_route(
        "/downloadWithFilename",
        lambda request: (
            request.setHeader("Content-Type", "application/octet-stream"),
            request.setHeader("Content-Disposition", "attachment; filename=file.txt"),
            request.write(b"Hello world"),
            request.finish(),
        ),
    )
    page = browser.new_page(accept_downloads=True)
    page.set_content(f'<a href="{server.PREFIX}/downloadWithFilename">download</a>')

    with page.expect_event("download") as download:
        page.click("a")
    assert download.value
    assert download.value.suggested_filename == "file.txt"
    path = download.value.path()
    assert os.path.isfile(path)
    with open(path, "r") as fd:
        assert fd.read() == "Hello world"
    page.close()
Example #31
0
async def test_should_disambiguate_by_header(browser: Browser, server: Server,
                                             assetdir: Path,
                                             tmpdir: Path) -> None:
    server.set_route(
        "/echo", lambda req:
        (req.write(req.getHeader("baz").encode()), req.finish()))
    fetch_function = """
        async (bazValue) => {
            const response = await fetch('/echo', {
            method: 'POST',
            body: '',
            headers: {
                foo: 'foo-value',
                bar: 'bar-value',
                baz: bazValue,
            }
            });
            return await response.text();
        };
    """
    har_path = tmpdir / "har.zip"
    context_1 = await browser.new_context(record_har_mode="minimal",
                                          record_har_path=har_path)
    page_1 = await context_1.new_page()
    await page_1.goto(server.EMPTY_PAGE)

    assert await page_1.evaluate(fetch_function, "baz1") == "baz1"
    assert await page_1.evaluate(fetch_function, "baz2") == "baz2"
    assert await page_1.evaluate(fetch_function, "baz3") == "baz3"
    await context_1.close()

    context_2 = await browser.new_context()
    await context_2.route_from_har(har=har_path)
    page_2 = await context_2.new_page()
    await page_2.goto(server.EMPTY_PAGE)
    assert await page_2.evaluate(fetch_function, "baz1") == "baz1"
    assert await page_2.evaluate(fetch_function, "baz2") == "baz2"
    assert await page_2.evaluate(fetch_function, "baz3") == "baz3"
    assert await page_2.evaluate(fetch_function, "baz4") == "baz1"
Example #32
0
    def test_functionality(self):
        port = 8080
        for fmt in SUPPORTED_FILE_FORMATS:
            sync_address = "127.0.0.1:" + str(port) + "/dummy.tar.gz"
            orig_tempdir = TemporaryDirectory()
            orig_path = os.path.join(orig_tempdir.name, "db")
            os.makedirs(orig_path)
            orig_db = PackageDB(orig_path, preferred_category_format=fmt)
            orig_db.add_category("app-test1")
            orig_db.add_category("app-test2")
            ebuild_data = {"test1": "tst1", "test2": "tst2",
                           "test3": serializable_elist([DeserializableClass("1", "2"),
                                                        DeserializableClass("3", "4")])}
            common_data = {"common1": "cmn1", "common2": "cmn2",
                           "common3": serializable_elist([DeserializableClass("c1", "c2"),
                                                          DeserializableClass("c3", "c4")])}
            packages = [Package("app-test1", "test", "1"), Package("app-test1", "test", "2"),
                        Package("app-test1", "test1", "1"), Package("app-test2", "test2", "1")]
            for package in packages:
                orig_db.add_package(package, ebuild_data)
            orig_db.set_common_data("app-test1", common_data)
            full_data = dict(ebuild_data)
            full_data.update(common_data)

            orig_db.write()
            os.system("cd " + orig_tempdir.name + " && tar cvzf good.tar.gz db")
            os.system("echo invalid >> " + orig_tempdir.name + "/db/app-test1/packages." + fmt)
            os.system("cd " + orig_tempdir.name + " && tar cvzf dummy.tar.gz db")

            test_db = PackageDB(self.tempdir.name)
            self.assertRaises(SyncError, test_db.sync, sync_address)

            srv = Server(orig_tempdir.name, port=port)
            srv.start()
            self.assertRaises(IntegrityError, test_db.sync, sync_address)
            os.system("cd " + orig_tempdir.name + " && mv good.tar.gz dummy.tar.gz")
            test_db.sync(sync_address)
            srv.shutdown()
            srv.join()
            test_db.read()
            self.assertEqual(orig_db.database, test_db.database)
            self.assertEqual(orig_db.get_common_data("app-test1"), test_db.get_common_data("app-test1"))
            self.assertEqual(orig_db.get_common_data("app-test2"), test_db.get_common_data("app-test2"))
            self.assertEqual(set(test_db.list_categories()), set(["app-test1", "app-test2"]))
            self.assertTrue(test_db.in_category("app-test1", "test"))
            self.assertFalse(test_db.in_category("app-test2", "test"))
            self.assertRaises(InvalidKeyError, test_db.in_category, "app-test3", "test")
            self.assertEqual(set(test_db.list_package_names("app-test1")), set(['test', 'test1']))
            self.assertEqual(set(test_db.list_catpkg_names()),set(['app-test1/test', 'app-test1/test1', 'app-test2/test2']))
            self.assertRaises(InvalidKeyError, test_db.list_package_versions, "invalid", "test")
            self.assertRaises(InvalidKeyError, test_db.list_package_versions, "app-test1", "invalid")
            self.assertEqual(set(test_db.list_package_versions("app-test1", "test")), set(['1', '2']))
            self.assertEqual(set(test_db.list_all_packages()), set(packages))
            self.assertEqual(test_db.get_package_description(packages[0]), full_data)
            self.assertRaises(KeyError, test_db.get_package_description, Package("invalid", "invalid", "1"))
            self.assertEqual(test_db.get_max_version("app-test1", "test"), "2")
            self.assertEqual(test_db.get_max_version("app-test1", "test1"), "1")
            self.assertRaises(InvalidKeyError, test_db.get_max_version, "invalid", "invalid")
            pkg_set = set(packages)
            for package, data in test_db:
                self.assertTrue(package in pkg_set)
                if package.category == "app-test1":
                    self.assertEqual(data, full_data)
                else:
                    self.assertEqual(data, ebuild_data)
                pkg_set.remove(package)
            self.assertTrue(not pkg_set)
            self.assertEqual(orig_db.database, test_db.database)
            port = port + 1