def test_should_round_trip_through_the_file(browser: Browser,
                                            context: BrowserContext,
                                            tmpdir: Path) -> None:
    page1 = context.new_page()
    page1.route(
        "**/*",
        lambda route: route.fulfill(body="<html></html>"),
    )
    page1.goto("https://www.example.com")
    page1.evaluate("""() => {
            localStorage["name1"] = "value1"
            document.cookie = "username=John Doe"
            return document.cookie
        }""")

    path = tmpdir / "storage-state.json"
    state = context.storage_state(path=path)
    with open(path, "r") as f:
        written = json.load(f)
    assert state == written

    context2 = browser.new_context(storage_state=path)
    page2 = context2.new_page()
    page2.route(
        "**/*",
        lambda route: route.fulfill(body="<html></html>"),
    )
    page2.goto("https://www.example.com")
    local_storage = page2.evaluate("window.localStorage")
    assert local_storage == {"name1": "value1"}
    cookie = page2.evaluate("document.cookie")
    assert cookie == "username=John Doe"
    context2.close()
Ejemplo n.º 2
0
def test_response_security_details(
    browser: Browser, https_server: Server, browser_name, is_win, is_linux
):
    if browser_name == "webkit" and is_linux:
        pytest.skip("https://github.com/microsoft/playwright/issues/6759")
    page = browser.new_page(ignore_https_errors=True)
    response = page.goto(https_server.EMPTY_PAGE)
    response.finished()
    security_details = response.security_details()
    assert security_details
    if browser_name == "webkit" and is_win:
        assert security_details == {
            "subjectName": "puppeteer-tests",
            "validFrom": 1550084863,
            "validTo": -1,
        }
    elif browser_name == "webkit":
        assert security_details == {
            "protocol": "TLS 1.3",
            "subjectName": "puppeteer-tests",
            "validFrom": 1550084863,
            "validTo": 33086084863,
        }
    else:
        assert security_details == {
            "issuer": "puppeteer-tests",
            "protocol": "TLS 1.3",
            "subjectName": "puppeteer-tests",
            "validFrom": 1550084863,
            "validTo": 33086084863,
        }
    page.close()
Ejemplo n.º 3
0
def test_should_not_break_page_close(browser: Browser) -> None:
    context = browser.new_context()
    page = context.new_page()
    session = page.context.new_cdp_session(page)
    session.detach()
    page.close()
    context.close()
def test_bounding_box_with_page_scale(browser: Browser, server: Server) -> None:
    context = browser.new_context(
        viewport={"width": 400, "height": 400}, is_mobile=True
    )
    page = context.new_page()
    page.goto(server.PREFIX + "/input/button.html")
    button = page.query_selector("button")
    assert button
    button.evaluate(
        """button => {
            document.body.style.margin = '0'
            button.style.borderWidth = '0'
            button.style.width = '200px'
            button.style.height = '20px'
            button.style.marginLeft = '17px'
            button.style.marginTop = '23px'
        }"""
    )

    box = button.bounding_box()
    assert box
    assert round(box["x"] * 100) == 17 * 100
    assert round(box["y"] * 100) == 23 * 100
    assert round(box["width"] * 100) == 200 * 100
    assert round(box["height"] * 100) == 20 * 100
    context.close()
Ejemplo n.º 5
0
def test_assertions_page_to_have_url_with_base_url(browser: Browser,
                                                   server: Server) -> None:
    page = browser.new_page(base_url=server.PREFIX)
    page.goto("/empty.html")
    expect(page).to_have_url("/empty.html")
    expect(page).to_have_url(re.compile(r".*/empty\.html"))
    page.close()
Ejemplo n.º 6
0
def test_should_allow_service_workers_by_default(
    browser: Browser, server: Server
) -> None:
    context = browser.new_context()
    page = context.new_page()
    page.goto(server.PREFIX + "/serviceworkers/fetchdummy/sw.html")
    page.evaluate("() => window.activationPromise")
    context.close()
Ejemplo n.º 7
0
def _context(
    browser: Browser,
    pytestconfig: t.Any,
    request: pytest.FixtureRequest,
) -> t.Generator[BrowserContext, None, None]:
    context = browser.new_context()
    yield context
    context.close()
Ejemplo n.º 8
0
def test_should_detach_when_page_closes(browser: Browser) -> None:
    context = browser.new_context()
    page = context.new_page()
    session = context.new_cdp_session(page)
    page.close()
    with pytest.raises(Error):
        session.detach()
    context.close()
Ejemplo n.º 9
0
def test_browser_context_output_trace(browser: Browser, server: Server,
                                      tmp_path: Path) -> None:
    context = browser.new_context()
    context.tracing.start(screenshots=True, snapshots=True)
    page = context.new_page()
    page.goto(server.PREFIX + "/grid.html")
    context.tracing.stop(path=tmp_path / "trace.zip")
    assert Path(tmp_path / "trace.zip").exists()
Ejemplo n.º 10
0
def reporting_fixture(browser: Browser, request):
    p: Page = browser.new_page()
    # p: Page = browser.new_page(record_video_dir="video/")
    p.context.clear_cookies()
    yield p
    screenshot = p.screenshot(path=f"screenshots/{request.node.name}.png", full_page=True)
    # video = p.video.path()
    p.close()
    allure.attach(screenshot, name=f"{request.node.name}", attachment_type=allure.attachment_type.PNG)
Ejemplo n.º 11
0
def test_should_work(browser: Browser, server: Server, tmpdir: Path) -> None:
    path = os.path.join(tmpdir, "log.har")
    context = browser.new_context(record_har_path=path)
    page = context.new_page()
    page.goto(server.EMPTY_PAGE)
    context.close()
    with open(path) as f:
        data = json.load(f)
        assert "log" in data
Ejemplo n.º 12
0
def test_block_blocks_service_worker_registration(
    browser: Browser, server: Server
) -> None:
    context = browser.new_context(service_workers="block")
    page = context.new_page()
    with page.expect_console_message(
        lambda m: "Service Worker registration blocked by Playwright" == m.text
    ):
        page.goto(server.PREFIX + "/serviceworkers/fetchdummy/sw.html")
    context.close()
Ejemplo n.º 13
0
def test_record_video_to_path(browser: Browser, tmpdir: Path,
                              server: Server) -> None:
    page = browser.new_page(record_video_dir=tmpdir)
    page.goto(server.PREFIX + "/grid.html")
    video = page.video
    assert video
    path = video.path()
    assert str(tmpdir) in str(path)
    page.wait_for_timeout(1000)
    page.context.close()
    assert os.path.exists(path)
Ejemplo n.º 14
0
def context(browser: Browser, browser_context_args: Dict, browser_name,
            video_path, request) -> Generator[BrowserContext, None, None]:
    context = browser.new_context(**browser_context_args)
    current_failed_tests = request.session.testsfailed
    yield context
    current_video_name = context.current_video_name
    current_video_path = current_video_name
    updated_video_path = os.path.join(
        video_path, f"{request.node.originalname}_{browser_name}.mp4")
    context.close()
    os.rename(current_video_path, updated_video_path)
Ejemplo n.º 15
0
def _context(
    browser: Browser,
    pytestconfig: t.Any,
    request: pytest.FixtureRequest,
) -> t.Generator[BrowserContext, None, None]:
    pages: t.List[Page] = []
    context = browser.new_context()
    context.on("page", lambda page: pages.append(page))  # pylint: disable=unnecessary-lambda
    yield context
    try:
        _may_create_screenshot(request, pytestconfig, pages)
    finally:
        context.close()
Ejemplo n.º 16
0
def test_should_expose_video_path(browser: Browser, tmpdir: Path,
                                  server: Server) -> None:
    page = browser.new_page(record_video_dir=tmpdir,
                            record_video_size={
                                "width": 100,
                                "height": 200
                            })
    page.goto(server.PREFIX + "/grid.html")
    video = page.video
    assert video
    path = video.path()
    assert repr(page.video) == f"<Video page={page}>"
    assert str(tmpdir) in str(path)
    page.wait_for_timeout(1000)
    page.context.close()
Ejemplo n.º 17
0
def test_should_omit_content(browser: Browser, server: Server,
                             tmpdir: Path) -> None:
    path = os.path.join(tmpdir, "log.har")
    context = browser.new_context(record_har_path=path,
                                  record_har_omit_content=True)
    page = context.new_page()
    page.goto(server.PREFIX + "/har.html")
    context.close()
    with open(path) as f:
        data = json.load(f)
        assert "log" in data
        log = data["log"]

        content1 = log["entries"][0]["response"]["content"]
        assert "text" not in content1
def test_selectors_register_should_work(selectors: Selectors, browser: Browser,
                                        browser_name: str) -> None:
    tag_selector = """
        {
            create(root, target) {
                return target.nodeName;
            },
            query(root, selector) {
                return root.querySelector(selector);
            },
            queryAll(root, selector) {
                return Array.from(root.querySelectorAll(selector));
            }
        }"""

    selector_name = f"tag_{browser_name}"
    selector2_name = f"tag2_{browser_name}"

    # Register one engine before creating context.
    selectors.register(selector_name, tag_selector)

    context = browser.new_context()
    # Register another engine after creating context.
    selectors.register(selector2_name, tag_selector)

    page = context.new_page()
    page.set_content("<div><span></span></div><div></div>")

    assert page.eval_on_selector(f"{selector_name}=DIV",
                                 "e => e.nodeName") == "DIV"
    assert page.eval_on_selector(f"{selector_name}=SPAN",
                                 "e => e.nodeName") == "SPAN"
    assert page.eval_on_selector_all(f"{selector_name}=DIV",
                                     "es => es.length") == 2

    assert page.eval_on_selector(f"{selector2_name}=DIV",
                                 "e => e.nodeName") == "DIV"
    assert page.eval_on_selector(f"{selector2_name}=SPAN",
                                 "e => e.nodeName") == "SPAN"
    assert page.eval_on_selector_all(f"{selector2_name}=DIV",
                                     "es => es.length") == 2

    # Selector names are case-sensitive.
    with pytest.raises(Error) as exc:
        page.query_selector("tAG=DIV")
    assert 'Unknown engine "tAG" while parsing selector tAG=DIV' in exc.value.message

    context.close()
def test_should_work_for_ssl(
    browser: Browser, https_server: Server, is_mac: bool, is_webkit: bool
) -> None:
    if is_webkit and is_mac:
        pytest.skip()
    page = browser.new_page(ignore_https_errors=True)
    with page.expect_event("requestfinished") as request_info:
        page.goto(https_server.EMPTY_PAGE)
    request = request_info.value
    timing = request.timing
    verify_connections_timing_consistency(timing)
    assert timing["requestStart"] >= timing["connectEnd"]
    assert timing["responseStart"] >= timing["requestStart"]
    assert timing["responseEnd"] >= timing["responseStart"]
    assert timing["responseEnd"] < 10000
    page.close()
def logout_fixture(browser: Browser, request):
    p: Page = browser.newPage()  # browser.newPage(videosPath="video/")
    p.context.clearCookies()
    yield p
    # Logout
    # main_page = MainPage(base_url, p)
    # if p.innerText(main_page.account_button(username).selector) is not None or "":
    #     settings_page = main_page.open_settings()
    #     settings_page.logout()
    screenshot = p.screenshot(path=f"screenshots/{request.node.name}.png",
                              fullPage=True)
    # video = p.video.path()
    p.close()
    allure.attach(screenshot,
                  name=f"{request.node.name}",
                  attachment_type=allure.attachment_type.PNG)
Ejemplo n.º 21
0
def test_should_include_content(browser: Browser, server: Server,
                                tmpdir: Path) -> None:
    path = os.path.join(tmpdir, "log.har")
    context = browser.new_context(record_har_path=path)
    page = context.new_page()
    page.goto(server.PREFIX + "/har.html")
    context.close()
    with open(path) as f:
        data = json.load(f)
        assert "log" in data
        log = data["log"]

        content1 = log["entries"][0]["response"]["content"]
        assert content1["encoding"] == "base64"
        assert content1["mimeType"] == "text/html"
        s = base64.b64decode(content1["text"]).decode()
        assert "HAR Page" in s
Ejemplo n.º 22
0
def test_browser_context_output_trace_chunk(browser: Browser, server: Server,
                                            tmp_path: Path) -> None:
    context = browser.new_context()
    context.tracing.start(screenshots=True, snapshots=True)
    page = context.new_page()
    page.goto(server.PREFIX + "/grid.html")
    button = page.locator(".box").first

    context.tracing.start_chunk(title="foo")
    button.click()
    context.tracing.stop_chunk(path=tmp_path / "trace1.zip")
    assert Path(tmp_path / "trace1.zip").exists()

    context.tracing.start_chunk(title="foo")
    button.click()
    context.tracing.stop_chunk(path=tmp_path / "trace2.zip")
    assert Path(tmp_path / "trace2.zip").exists()
def test_should_set_local_storage(browser: Browser) -> None:
    context = browser.new_context(
        storage_state={
            "origins": [{
                "origin": "https://www.example.com",
                "localStorage": [{
                    "name": "name1",
                    "value": "value1"
                }],
            }]
        })

    page = context.new_page()
    page.route("**/*", lambda route: route.fulfill(body="<html></html>"))
    page.goto("https://www.example.com")
    local_storage = page.evaluate("window.localStorage")
    assert local_storage == {"name1": "value1"}
    context.close()
Ejemplo n.º 24
0
def get_shutterstock_image_by_id(id: str,
                                 output_dir: str,
                                 browser: Browser = None):
    page = browser.new_page()
    page.goto("https://www.shutterstock.com/")
    search_input = page.locator("input[type=\"search\"]")
    search_input.fill(str(id))
    search_button = page.locator("button[aria-label=\"Search\"]")
    search_button.click()
    div_a_wrapper = page.locator(
        "div[data-automation=\"AssetGrids_MosaicAssetGrid_div\"]").first
    src = div_a_wrapper.locator('img').first.get_attribute('src')
    if not os.path.isdir(output_dir):
        os.mkdir(output_dir)
    file_location = os.path.join(output_dir, os.path.basename(src))
    urllib.request.urlretrieve(src, file_location)
    page.close()
    return ImageInfo(id, file_location)
def logout_fixture(browser: Browser, request):
    # p: Page = browser.new_page()
    p: Page = browser.new_page(record_video_dir="video/")
    p.context.clear_cookies()
    yield p
    # Logout
    # main_page = MainPage(base_url, p)
    # if p.inner_text(main_page.account_button(username).selector) is not None or "":
    #     settings_page = main_page.open_settings()
    #     settings_page.logout()
    screenshot = p.screenshot(path=f"screenshots/{request.node.name}.png",
                              full_page=True)
    video = p.video.path()
    p.close()
    allure.attach(screenshot,
                  name=f"{request.node.name}",
                  attachment_type=allure.attachment_type.PNG)
    allure.attach.file(f'./{video}',
                       attachment_type=allure.attachment_type.WEBM)
def test_should_work_for_ssl(browser: Browser, https_server: Server,
                             is_mac: bool, is_webkit: bool) -> None:
    if is_webkit and is_mac:
        pytest.skip()
    page = browser.new_page(ignore_https_errors=True)
    with page.expect_event("requestfinished") as request_info:
        page.goto(https_server.EMPTY_PAGE)
    request = request_info.value
    timing = request.timing
    if not (is_webkit and is_mac):
        assert timing["domainLookupStart"] >= -1
        assert timing["domainLookupEnd"] >= timing["domainLookupStart"]
        assert timing["connectStart"] >= timing["domainLookupEnd"]
        assert timing["secureConnectionStart"] > timing["connectStart"]
        assert timing["connectEnd"] > timing["secureConnectionStart"]
        assert timing["requestStart"] >= timing["connectEnd"]

    assert timing["responseStart"] > timing["requestStart"]
    assert timing["responseEnd"] >= timing["responseStart"]
    assert timing["responseEnd"] < 10000
    page.close()
Ejemplo n.º 27
0
def get_shutterstock_image_by_image(image_location: str,
                                    output_dir: str,
                                    browser: Browser = None):
    page = browser.new_page()
    page.goto("https://www.shutterstock.com/")
    listbox = page.locator("[aria-haspopup=\"listbox\"][aria-label=\"Image\"]")
    listbox.click()
    listbox_item = page.locator("[data-value=\"reverseImageSearch\"]")
    listbox_item.click()
    file_input = page.locator("input[type=\"file\"]")
    file_input.set_input_files(image_location)
    imageLink = page.locator("a[data-track-label=\"gridItem\"]").first
    image_info = imageLink.get_attribute('data-track-value')
    id = json.loads(image_info)['id']
    src = imageLink.locator('img').first.get_attribute('src')
    if not os.path.isdir(output_dir):
        os.mkdir(output_dir)
    file_location = os.path.join(output_dir, os.path.basename(src))
    urllib.request.urlretrieve(src, file_location)
    page.close()
    return ImageInfo(id, file_location)
Ejemplo n.º 28
0
def test_sync_download(browser: Browser, server):
    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.newPage(acceptDownloads=True)
    page.setContent(f'<a href="{server.PREFIX}/downloadWithFilename">download</a>')

    with page.expect_event("download") as download:
        page.click("a")
    assert download.value
    assert download.value.suggestedFilename == "file.txt"
    path = download.value.path()
    assert os.path.isfile(path)
    with open(path, "r") as fd:
        assert fd.read() == "Hello world"
    page.close()
Ejemplo n.º 29
0
def context(browser: Browser) -> Generator[BrowserContext, None, None]:
    context = browser.new_context()
    yield context
    context.close()
def context(
        browser: Browser,
        browser_context_args: Dict) -> Generator[BrowserContext, None, None]:
    context = browser.new_context(**browser_context_args)
    yield context
    context.close()