async def test_locators_frame_should_work_with_locator_frame_locator( page: Page, server: Server) -> None: await route_iframe(page) await page.goto(server.EMPTY_PAGE) button = page.locator("body").frame_locator("iframe").locator("button") await button.wait_for() assert await button.inner_text() == "Hello iframe" await button.click()
async def test_locators_focus_should_work(page: Page, server: Server): await page.goto(server.PREFIX + "/input/button.html") button = page.locator("button") assert await button.evaluate("button => document.activeElement === button" ) is False await button.focus() assert await button.evaluate("button => document.activeElement === button" ) is True
async def test_locators_should_have_repr(page: Page, server: Server): await page.goto(server.PREFIX + "/input/button.html") button = page.locator("button") await button.click() assert ( str(button) == f"<Locator frame=<Frame name= url='{server.PREFIX}/input/button.html'> selector='button'>" )
async def test_locators_return_empty_array_for_non_existing_elements( page: Page): await page.set_content( """<html><body><div>A</div><br/><div>B</div></body></html>""") html = page.locator("html") elements = await html.locator("abc").element_handles() assert len(elements) == 0 assert elements == []
async def test_locators_wait_for(page: Page) -> None: await page.set_content("<div></div>") locator = page.locator("div") task = locator.wait_for() await page.eval_on_selector( "div", "div => div.innerHTML = '<span>target</span>'") await task assert await locator.text_content() == "target"
async def test_locators_is_checked_should_work(page: Page): await page.set_content(""" <input type='checkbox' checked><div>Not a checkbox</div> """) element = page.locator("input") assert await element.is_checked() is True await element.evaluate("e => e.checked = false") assert await element.is_checked() is False
async def test_locators_is_enabled_and_is_disabled_should_work(page: Page): await page.set_content(""" <button disabled>button1</button> <button>button2</button> <div>div</div> """) div = page.locator("div") assert await div.is_enabled() is True assert await div.is_disabled() is False button1 = page.locator(':text("button1")') assert await button1.is_enabled() is False assert await button1.is_disabled() is True button1 = page.locator(':text("button2")') assert await button1.is_enabled() is True assert await button1.is_disabled() is False
async def test_drag_to(page: Page, server: Server) -> None: await page.goto(server.PREFIX + "/drag-n-drop.html") await page.locator("#source").drag_to(page.locator("#target")) assert ( await page.eval_on_selector( "#target", "target => target.contains(document.querySelector('#source'))" ) is True )
async def test_locators_all_inner_texts(page: Page): await page.set_content( """ <div>A</div><div>B</div><div>C</div> """ ) element = page.locator("div") assert await element.all_inner_texts() == ["A", "B", "C"]
async def test_assertions_should_serialize_regexp_correctly( page: Page, server: Server) -> None: await page.goto(server.EMPTY_PAGE) await page.set_content("<div>iGnOrEcAsE</div>") await expect(page.locator("div") ).to_have_text(re.compile(r"ignorecase", re.IGNORECASE)) await page.set_content("""<div>start some lines between end</div>""") await expect(page.locator("div") ).to_have_text(re.compile(r"start.*end", re.DOTALL)) await page.set_content("""<div>line1 line2 line3</div>""") await expect(page.locator("div") ).to_have_text(re.compile(r"^line2$", re.MULTILINE))
async def test_assertions_locator_to_have_value(page: Page, server: Server) -> None: await page.goto(server.EMPTY_PAGE) await page.set_content("<input type=text id=foo>") my_input = page.locator("#foo") await expect(my_input).to_have_value("") await expect(my_input).not_to_have_value("bar", timeout=100) await my_input.fill("kektus") await expect(my_input).to_have_value("kektus")
async def test_locators_should_upload_a_file(page: Page, server: Server): await page.goto(server.PREFIX + "/input/fileupload.html") input = page.locator("input[type=file]") file_path = os.path.relpath(FILE_TO_UPLOAD, os.getcwd()) await input.set_input_files(file_path) assert (await page.evaluate("e => e.files[0].name", await input.element_handle()) == "file-to-upload.txt")
async def test_assertions_locator_to_be_focused(page: Page, server: Server) -> None: await page.goto(server.EMPTY_PAGE) await page.set_content("<input type=checkbox>") my_checkbox = page.locator("input") with pytest.raises(AssertionError): await expect(my_checkbox).to_be_focused(timeout=100) await my_checkbox.focus() await expect(my_checkbox).to_be_focused()
async def test_should_page_route_from_har_matching_the_method_and_following_redirects( page: Page, assetdir: Path) -> None: await page.route_from_har(har=assetdir / "har-fulfill.har") await page.goto("http://no.playwright/") # HAR contains a redirect for the script that should be followed automatically. assert await page.evaluate("window.value") == "foo" # HAR contains a POST for the css file that should not be used. await expect(page.locator("body")).to_have_css("background-color", "rgb(255, 0, 0)")
async def test_locators_should_query_existing_elements(page: Page): await page.set_content( """<html><body><div>A</div><br/><div>B</div></body></html>""") html = page.locator("html") elements = await html.locator("div").element_handles() assert len(elements) == 2 result = [] for element in elements: result.append(await page.evaluate("e => e.textContent", element)) assert result == ["A", "B"]
async def test_locator_should_return_page(page: Page, server: Server) -> None: await page.goto(server.PREFIX + "/frames/two-frames.html") outer = page.locator("#outer") assert outer.page == page inner = outer.locator("#inner") assert inner.page == page in_frame = page.frames[1].locator("div") assert in_frame.page == page
async def test_locators_should_screenshot(page: Page, server: Server, assert_to_be_golden): await page.set_viewport_size({ "width": 500, "height": 500, }) await page.goto(server.PREFIX + "/grid.html") await page.evaluate("window.scrollBy(50, 100)") element = page.locator(".box:nth-of-type(3)") assert_to_be_golden(await element.screenshot(), "screenshot-element-bounding-box.png")
async def test_locator_frame_locator_should_throw_on_ambiguity( page: Page, server: Server) -> None: await route_ambiguous(page) await page.goto(server.EMPTY_PAGE) button = page.locator("body").frame_locator("iframe").locator("button") with pytest.raises( Error, match= '.*strict mode violation: "body >> iframe" resolved to 3 elements.*', ): await button.wait_for()
async def test_locators_should_query_existing_element(page: Page, server: Server): await page.goto(server.PREFIX + "/playground.html") await page.set_content( """<html><body><div class="second"><div class="inner">A</div></div></body></html>""" ) html = page.locator("html") second = html.locator(".second") inner = second.locator(".inner") assert (await page.evaluate("e => e.textContent", await inner.element_handle()) == "A")
async def test_assertions_locator_to_have_js_property( page: Page, server: Server ) -> None: await page.goto(server.EMPTY_PAGE) await page.set_content("<div></div>") await page.eval_on_selector( "div", "e => e.foo = { a: 1, b: 'string', c: new Date(1627503992000) }" ) await expect(page.locator("div")).to_have_js_property( "foo", {"a": 1, "b": "string", "c": datetime.utcfromtimestamp(1627503992000 / 1000)}, )
async def test_locators_should_select_textarea(page: Page, server: Server, browser_name: str): await page.goto(server.PREFIX + "/input/textarea.html") textarea = page.locator("textarea") await textarea.evaluate("textarea => textarea.value = 'some value'") await textarea.select_text() if browser_name == "firefox": assert await textarea.evaluate("el => el.selectionStart") == 0 assert await textarea.evaluate("el => el.selectionEnd") == 10 else: assert await page.evaluate("window.getSelection().toString()" ) == "some value"
async def test_to_have_values_fails_when_not_a_select_element( page: Page, server: Server ) -> None: await page.set_content( """ <input type="text"> """ ) locator = page.locator("input") with pytest.raises(Error) as excinfo: await expect(locator).to_have_values(["R", "G"], timeout=500) assert "Error: Not a select element with a multiple attribute" in str(excinfo.value)
async def test_should_screenshot_with_mask(page: Page, server: Server, assert_to_be_golden): await page.set_viewport_size({ "width": 500, "height": 500, }) await page.goto(server.PREFIX + "/grid.html") assert_to_be_golden( await page.screenshot(mask=[page.locator("div").nth(5)]), "mask-should-work-with-page.png", ) assert_to_be_golden( await page.locator("body").screenshot(mask=[page.locator("div").nth(5)]), "mask-should-work-with-locator.png", ) assert_to_be_golden( await (await page.query_selector("body")).screenshot( mask=[page.locator("div").nth(5)]), "mask-should-work-with-element-handle.png", )
async def test_ignore_case(page: Page, server: Server, method: str) -> None: await page.goto(server.EMPTY_PAGE) await page.set_content("<div id=target>apple BANANA</div><div>orange</div>") await getattr(expect(page.locator("div#target")), method)("apple BANANA") await getattr(expect(page.locator("div#target")), method)( "apple banana", ignore_case=True ) # defaults false with pytest.raises(AssertionError) as excinfo: await getattr(expect(page.locator("div#target")), method)( "apple banana", timeout=300 ) expected_error_msg = method.replace("_", " ") assert expected_error_msg in str(excinfo.value) # Array Variants await getattr(expect(page.locator("div")), method)(["apple BANANA", "orange"]) await getattr(expect(page.locator("div")), method)( ["apple banana", "ORANGE"], ignore_case=True ) # defaults false with pytest.raises(AssertionError) as excinfo: await getattr(expect(page.locator("div")), method)( ["apple banana", "ORANGE"], timeout=300 ) assert expected_error_msg in str(excinfo.value) # not variant await getattr(expect(page.locator("div#target")), f"not_{method}")("apple banana") with pytest.raises(AssertionError) as excinfo: await getattr(expect(page.locator("div#target")), f"not_{method}")( "apple banana", ignore_case=True, timeout=300 ) assert f"not {expected_error_msg}" in str(excinfo)
async def test_assertions_locator_to_be_hidden_visible(page: Page, server: Server) -> None: await page.goto(server.EMPTY_PAGE) await page.set_content( "<div style='width: 50px; height: 50px;'>Something</div>") my_checkbox = page.locator("div") await expect(my_checkbox).to_be_visible() with pytest.raises(AssertionError): await expect(my_checkbox).to_be_hidden(timeout=100) await my_checkbox.evaluate("e => e.style.display = 'none'") await expect(my_checkbox).to_be_hidden() with pytest.raises(AssertionError): await expect(my_checkbox).to_be_visible(timeout=100)
async def test_assertions_locator_to_be_disabled_enabled( page: Page, server: Server) -> None: await page.goto(server.EMPTY_PAGE) await page.set_content("<input type=checkbox>") my_checkbox = page.locator("input") await expect(my_checkbox).not_to_be_disabled() await expect(my_checkbox).to_be_enabled() with pytest.raises(AssertionError): await expect(my_checkbox).to_be_disabled(timeout=100) await my_checkbox.evaluate("e => e.disabled = true") await expect(my_checkbox).to_be_disabled() with pytest.raises(AssertionError): await expect(my_checkbox).to_be_enabled(timeout=100)
async def test_to_have_values_works_with_regex(page: Page, server: Server) -> None: await page.set_content( """ <select multiple> <option value="R">Red</option> <option value="G">Green</option> <option value="B">Blue</option> </select> """ ) locator = page.locator("select") await locator.select_option(["R", "G"]) await expect(locator).to_have_values([re.compile("R"), re.compile("G")])
async def test_drag_to_with_position(page: Page, server: Server): await page.goto(server.EMPTY_PAGE) await page.set_content(""" <div style="width:100px;height:100px;background:red;" id="red"> </div> <div style="width:100px;height:100px;background:blue;" id="blue"> </div> """) events_handle = await page.evaluate_handle(""" () => { const events = []; document.getElementById('red').addEventListener('mousedown', event => { events.push({ type: 'mousedown', x: event.offsetX, y: event.offsetY, }); }); document.getElementById('blue').addEventListener('mouseup', event => { events.push({ type: 'mouseup', x: event.offsetX, y: event.offsetY, }); }); return events; } """) await page.locator("#red").drag_to( page.locator("#blue"), source_position={ "x": 34, "y": 7 }, target_position={ "x": 10, "y": 20 }, ) assert await events_handle.json_value() == [ { "type": "mousedown", "x": 34, "y": 7 }, { "type": "mouseup", "x": 10, "y": 20 }, ]
async def test_to_have_values_follows_labels(page: Page, server: Server) -> None: await page.set_content( """ <label for="colors">Pick a Color</label> <select id="colors" multiple> <option value="R">Red</option> <option value="G">Green</option> <option value="B">Blue</option> </select> """ ) locator = page.locator("text=Pick a Color") await locator.select_option(["R", "G"]) await expect(locator).to_have_values(["R", "G"])
async def test_locators_click_should_work_for_text_nodes( page: Page, server: Server): await page.goto(server.PREFIX + "/input/button.html") await page.evaluate("""() => { window['double'] = false; const button = document.querySelector('button'); button.addEventListener('dblclick', event => { window['double'] = true; }); }""") button = page.locator("button") await button.dblclick() assert await page.evaluate("double") is True assert await page.evaluate("result") == "Clicked"