How to use expect_page method in Playwright Python

Best Python code snippet using playwright-python

test_browsercontext.py

Source:test_browsercontext.py Github

copy

Full Screen

...99 await context.close()100async def test_close_should_abort_wait_for_event(browser):101 context = await browser.new_context()102 with pytest.raises(Error) as exc_info:103 async with context.expect_page():104 await context.close()105 assert "Context closed" in exc_info.value.message106async def test_close_should_be_callable_twice(browser):107 context = await browser.new_context()108 await asyncio.gather(109 context.close(),110 context.close(),111 )112 await context.close()113async def test_user_agent_should_work(browser, server):114 async def baseline():115 context = await browser.new_context()116 page = await context.new_page()117 assert "Mozilla" in await page.evaluate("navigator.userAgent")118 await context.close()119 await baseline()120 async def override():121 context = await browser.new_context(user_agent="foobar")122 page = await context.new_page()123 [request, _] = await asyncio.gather(124 server.wait_for_request("/empty.html"),125 page.goto(server.EMPTY_PAGE),126 )127 assert request.getHeader("user-agent") == "foobar"128 await context.close()129 await override()130async def test_user_agent_should_work_for_subframes(browser, server, utils):131 context = await browser.new_context(user_agent="foobar")132 page = await context.new_page()133 [request, _] = await asyncio.gather(134 server.wait_for_request("/empty.html"),135 utils.attach_frame(page, "frame1", server.EMPTY_PAGE),136 )137 assert request.getHeader("user-agent") == "foobar"138 await context.close()139async def test_user_agent_should_emulate_device_user_agent(playwright, browser, server):140 context = await browser.new_context(141 user_agent=playwright.devices["iPhone 6"]["user_agent"]142 )143 page = await context.new_page()144 await page.goto(server.PREFIX + "/mobile.html")145 assert "iPhone" in await page.evaluate("navigator.userAgent")146 await context.close()147async def test_user_agent_should_make_a_copy_of_default_options(browser, server):148 options = {"user_agent": "foobar"}149 context = await browser.new_context(**options)150 options["user_agent"] = "wrong"151 page = await context.new_page()152 [request, _] = await asyncio.gather(153 server.wait_for_request("/empty.html"),154 page.goto(server.EMPTY_PAGE),155 )156 assert request.getHeader("user-agent") == "foobar"157 await context.close()158async def test_page_event_should_bypass_csp_meta_tag(browser, server):159 async def baseline():160 context = await browser.new_context()161 page = await context.new_page()162 await page.goto(server.PREFIX + "/csp.html")163 try:164 await page.add_script_tag(content="window.__injected = 42;")165 except Error:166 pass167 assert await page.evaluate("window.__injected") is None168 await context.close()169 await baseline()170 # By-pass CSP and try one more time.171 async def override():172 context = await browser.new_context(bypass_csp=True)173 page = await context.new_page()174 await page.goto(server.PREFIX + "/csp.html")175 await page.add_script_tag(content="window.__injected = 42;")176 assert await page.evaluate("() => window.__injected") == 42177 await context.close()178 await override()179async def test_page_event_should_bypass_csp_header(browser, server):180 # Make sure CSP prohibits add_script_tag.181 server.set_csp("/empty.html", 'default-src "self"')182 async def baseline():183 context = await browser.new_context()184 page = await context.new_page()185 await page.goto(server.EMPTY_PAGE)186 try:187 await page.add_script_tag(content="window.__injected = 42;")188 except Error:189 pass190 assert await page.evaluate("() => window.__injected") is None191 await context.close()192 await baseline()193 # By-pass CSP and try one more time.194 async def override():195 context = await browser.new_context(bypass_csp=True)196 page = await context.new_page()197 await page.goto(server.EMPTY_PAGE)198 await page.add_script_tag(content="window.__injected = 42;")199 assert await page.evaluate("window.__injected") == 42200 await context.close()201 await override()202async def test_page_event_should_bypass_after_cross_process_navigation(browser, server):203 context = await browser.new_context(bypass_csp=True)204 page = await context.new_page()205 await page.goto(server.PREFIX + "/csp.html")206 await page.add_script_tag(content="window.__injected = 42;")207 assert await page.evaluate("window.__injected") == 42208 await page.goto(server.CROSS_PROCESS_PREFIX + "/csp.html")209 await page.add_script_tag(content="window.__injected = 42;")210 assert await page.evaluate("window.__injected") == 42211 await context.close()212async def test_page_event_should_bypass_csp_in_iframes_as_well(browser, server, utils):213 async def baseline():214 # Make sure CSP prohibits add_script_tag in an iframe.215 context = await browser.new_context()216 page = await context.new_page()217 await page.goto(server.EMPTY_PAGE)218 frame = await utils.attach_frame(page, "frame1", server.PREFIX + "/csp.html")219 try:220 await frame.add_script_tag(content="window.__injected = 42;")221 except Error:222 pass223 assert await frame.evaluate("window.__injected") is None224 await context.close()225 await baseline()226 # By-pass CSP and try one more time.227 async def override():228 context = await browser.new_context(bypass_csp=True)229 page = await context.new_page()230 await page.goto(server.EMPTY_PAGE)231 frame = await utils.attach_frame(page, "frame1", server.PREFIX + "/csp.html")232 try:233 await frame.add_script_tag(content="window.__injected = 42;")234 except Error:235 pass236 assert await frame.evaluate("window.__injected") == 42237 await context.close()238 await override()239async def test_csp_should_work(browser, is_webkit):240 async def baseline():241 context = await browser.new_context(java_script_enabled=False)242 page = await context.new_page()243 await page.goto('data:text/html, <script>var something = "forbidden"</script>')244 with pytest.raises(Error) as exc_info:245 await page.evaluate("something")246 if is_webkit:247 assert "Can't find variable: something" in exc_info.value.message248 else:249 assert "something is not defined" in exc_info.value.message250 await context.close()251 await baseline()252 async def override():253 context = await browser.new_context()254 page = await context.new_page()255 await page.goto('data:text/html, <script>var something = "forbidden"</script>')256 assert await page.evaluate("something") == "forbidden"257 await context.close()258 await override()259async def test_csp_should_be_able_to_navigate_after_disabling_javascript(260 browser, server261):262 context = await browser.new_context(java_script_enabled=False)263 page = await context.new_page()264 await page.goto(server.EMPTY_PAGE)265 await context.close()266async def test_pages_should_return_all_of_the_pages(context, server):267 page = await context.new_page()268 second = await context.new_page()269 all_pages = context.pages270 assert len(all_pages) == 2271 assert page in all_pages272 assert second in all_pages273async def test_pages_should_close_all_belonging_pages_once_closing_context(context):274 await context.new_page()275 assert len(context.pages) == 1276 await context.close()277 assert context.pages == []278async def test_expose_binding_should_work(context):279 binding_source = []280 def binding(source, a, b):281 binding_source.append(source)282 return a + b283 await context.expose_binding("add", lambda source, a, b: binding(source, a, b))284 page = await context.new_page()285 result = await page.evaluate("add(5, 6)")286 assert binding_source[0]["context"] == context287 assert binding_source[0]["page"] == page288 assert binding_source[0]["frame"] == page.main_frame289 assert result == 11290async def test_expose_function_should_work(context):291 await context.expose_function("add", lambda a, b: a + b)292 page = await context.new_page()293 await page.expose_function("mul", lambda a, b: a * b)294 await context.expose_function("sub", lambda a, b: a - b)295 result = await page.evaluate(296 """async function() {297 return { mul: await mul(9, 4), add: await add(9, 4), sub: await sub(9, 4) }298 }"""299 )300 assert result == {"mul": 36, "add": 13, "sub": 5}301async def test_expose_function_should_throw_for_duplicate_registrations(302 context, server303):304 await context.expose_function("foo", lambda: None)305 await context.expose_function("bar", lambda: None)306 with pytest.raises(Error) as exc_info:307 await context.expose_function("foo", lambda: None)308 assert exc_info.value.message == 'Function "foo" has been already registered'309 page = await context.new_page()310 with pytest.raises(Error) as exc_info:311 await page.expose_function("foo", lambda: None)312 assert (313 exc_info.value.message314 == 'Function "foo" has been already registered in the browser context'315 )316 await page.expose_function("baz", lambda: None)317 with pytest.raises(Error) as exc_info:318 await context.expose_function("baz", lambda: None)319 assert (320 exc_info.value.message321 == 'Function "baz" has been already registered in one of the pages'322 )323async def test_expose_function_should_be_callable_from_inside_add_init_script(324 context, server325):326 args = []327 await context.expose_function("woof", lambda arg: args.append(arg))328 await context.add_init_script("woof('context')")329 page = await context.new_page()330 await page.add_init_script("woof('page')")331 args = []332 await page.reload()333 assert args == ["context", "page"]334async def test_expose_bindinghandle_should_work(context):335 targets = []336 def logme(t):337 targets.append(t)338 return 17339 page = await context.new_page()340 await page.expose_binding("logme", lambda source, t: logme(t), handle=True)341 result = await page.evaluate("logme({ foo: 42 })")342 assert (await targets[0].evaluate("x => x.foo")) == 42343 assert result == 17344async def test_route_should_intercept(context, server):345 intercepted = []346 def handle(route, request):347 intercepted.append(True)348 assert "empty.html" in request.url349 assert request.headers["user-agent"]350 assert request.method == "GET"351 assert request.post_data is None352 assert request.is_navigation_request353 assert request.resource_type == "document"354 assert request.frame == page.main_frame355 assert request.frame.url == "about:blank"356 asyncio.create_task(route.continue_())357 await context.route("**/empty.html", lambda route, request: handle(route, request))358 page = await context.new_page()359 response = await page.goto(server.EMPTY_PAGE)360 assert response.ok361 assert intercepted == [True]362 await context.close()363async def test_route_should_unroute(context, server):364 page = await context.new_page()365 intercepted = []366 def handler(route, request, ordinal):367 intercepted.append(ordinal)368 asyncio.create_task(route.continue_())369 def handler1(route, request):370 handler(route, request, 1)371 await context.route("**/empty.html", handler1)372 await context.route(373 "**/empty.html", lambda route, request: handler(route, request, 2)374 )375 await context.route(376 "**/empty.html", lambda route, request: handler(route, request, 3)377 )378 await context.route("**/*", lambda route, request: handler(route, request, 4))379 await page.goto(server.EMPTY_PAGE)380 assert intercepted == [1]381 intercepted = []382 await context.unroute("**/empty.html", handler1)383 await page.goto(server.EMPTY_PAGE)384 assert intercepted == [2]385 intercepted = []386 await context.unroute("**/empty.html")387 await page.goto(server.EMPTY_PAGE)388 assert intercepted == [4]389async def test_route_should_yield_to_page_route(context, server):390 await context.route(391 "**/empty.html",392 lambda route, request: asyncio.create_task(393 route.fulfill(status=200, body="context")394 ),395 )396 page = await context.new_page()397 await page.route(398 "**/empty.html",399 lambda route, request: asyncio.create_task(400 route.fulfill(status=200, body="page")401 ),402 )403 response = await page.goto(server.EMPTY_PAGE)404 assert response.ok405 assert await response.text() == "page"406async def test_route_should_fall_back_to_context_route(context, server):407 await context.route(408 "**/empty.html",409 lambda route, request: asyncio.create_task(410 route.fulfill(status=200, body="context")411 ),412 )413 page = await context.new_page()414 await page.route(415 "**/non-empty.html",416 lambda route, request: asyncio.create_task(417 route.fulfill(status=200, body="page")418 ),419 )420 response = await page.goto(server.EMPTY_PAGE)421 assert response.ok422 assert await response.text() == "context"423async def test_auth_should_fail_without_credentials(context, server):424 server.set_auth("/empty.html", b"user", b"pass")425 page = await context.new_page()426 response = await page.goto(server.EMPTY_PAGE)427 assert response.status == 401428async def test_auth_should_work_with_correct_credentials(browser, server):429 server.set_auth("/empty.html", b"user", b"pass")430 context = await browser.new_context(431 http_credentials={"username": "user", "password": "pass"}432 )433 page = await context.new_page()434 response = await page.goto(server.EMPTY_PAGE)435 assert response.status == 200436 await context.close()437async def test_auth_should_fail_with_wrong_credentials(browser, server):438 server.set_auth("/empty.html", b"user", b"pass")439 context = await browser.new_context(440 http_credentials={"username": "foo", "password": "bar"}441 )442 page = await context.new_page()443 response = await page.goto(server.EMPTY_PAGE)444 assert response.status == 401445 await context.close()446async def test_auth_should_return_resource_body(browser, server):447 server.set_auth("/playground.html", b"user", b"pass")448 context = await browser.new_context(449 http_credentials={"username": "user", "password": "pass"}450 )451 page = await context.new_page()452 response = await page.goto(server.PREFIX + "/playground.html")453 assert response.status == 200454 assert await page.title() == "Playground"455 assert "Playground" in await response.text()456 await context.close()457async def test_offline_should_work_with_initial_option(browser, server):458 context = await browser.new_context(offline=True)459 page = await context.new_page()460 with pytest.raises(Error) as exc_info:461 await page.goto(server.EMPTY_PAGE)462 assert exc_info.value463 await context.set_offline(False)464 response = await page.goto(server.EMPTY_PAGE)465 assert response.status == 200466 await context.close()467async def test_offline_should_emulate_navigator_online(context, server):468 page = await context.new_page()469 assert await page.evaluate("window.navigator.onLine")470 await context.set_offline(True)471 assert await page.evaluate("window.navigator.onLine") is False472 await context.set_offline(False)473 assert await page.evaluate("window.navigator.onLine")474async def test_page_event_should_have_url(context, server):475 page = await context.new_page()476 async with context.expect_page() as other_page_info:477 await page.evaluate("url => window.open(url)", server.EMPTY_PAGE)478 other_page = await other_page_info.value479 assert other_page.url == server.EMPTY_PAGE480async def test_page_event_should_have_url_after_domcontentloaded(context, server):481 page = await context.new_page()482 async with context.expect_page() as other_page_info:483 await page.evaluate("url => window.open(url)", server.EMPTY_PAGE)484 other_page = await other_page_info.value485 await other_page.wait_for_load_state("domcontentloaded")486 assert other_page.url == server.EMPTY_PAGE487async def test_page_event_should_have_about_blank_url_with_domcontentloaded(488 context, server489):490 page = await context.new_page()491 async with context.expect_page() as other_page_info:492 await page.evaluate("url => window.open(url)", "about:blank")493 other_page = await other_page_info.value494 await other_page.wait_for_load_state("domcontentloaded")495 assert other_page.url == "about:blank"496async def test_page_event_should_have_about_blank_for_empty_url_with_domcontentloaded(497 context, server498):499 page = await context.new_page()500 async with context.expect_page() as other_page_info:501 await page.evaluate("window.open()")502 other_page = await other_page_info.value503 await other_page.wait_for_load_state("domcontentloaded")504 assert other_page.url == "about:blank"505async def test_page_event_should_report_when_a_new_page_is_created_and_closed(506 context, server507):508 page = await context.new_page()509 async with context.expect_page() as page_info:510 await page.evaluate(511 "url => window.open(url)", server.CROSS_PROCESS_PREFIX + "/empty.html"512 )513 other_page = await page_info.value514 # The url is about:blank in FF when 'page' event is fired.515 assert server.CROSS_PROCESS_PREFIX in other_page.url516 assert await other_page.evaluate("['Hello', 'world'].join(' ')") == "Hello world"517 assert await other_page.query_selector("body")518 all_pages = context.pages519 assert page in all_pages520 assert other_page in all_pages521 close_event_received = []522 other_page.once("close", lambda: close_event_received.append(True))523 await other_page.close()524 assert close_event_received == [True]525 all_pages = context.pages526 assert page in all_pages527 assert other_page not in all_pages528async def test_page_event_should_report_initialized_pages(context, server):529 async with context.expect_page() as page_info:530 await context.new_page()531 new_page = await page_info.value532 assert new_page.url == "about:blank"533 async with context.expect_page() as popup_info:534 await new_page.evaluate("window.open('about:blank')")535 popup = await popup_info.value536 assert popup.url == "about:blank"537async def test_page_event_should_have_an_opener(context, server):538 page = await context.new_page()539 await page.goto(server.EMPTY_PAGE)540 async with context.expect_page() as page_info:541 await page.goto(server.PREFIX + "/popup/window-open.html"),542 popup = await page_info.value543 assert popup.url == server.PREFIX + "/popup/popup.html"544 assert await popup.opener() == page545 assert await page.opener() is None546async def test_page_event_should_fire_page_lifecycle_events(context, server):547 events = []548 def handle_page(page):549 events.append("CREATED: " + page.url)550 page.on("close", lambda: events.append("DESTROYED: " + page.url))551 context.on("page", handle_page)552 page = await context.new_page()553 await page.goto(server.EMPTY_PAGE)554 await page.close()555 assert events == ["CREATED: about:blank", f"DESTROYED: {server.EMPTY_PAGE}"]556@pytest.mark.skip_browser("webkit")557async def test_page_event_should_work_with_shift_clicking(context, server):558 # WebKit: Shift+Click does not open a new window.559 page = await context.new_page()560 await page.goto(server.EMPTY_PAGE)561 await page.set_content('<a href="/one-style.html">yo</a>')562 async with context.expect_page() as page_info:563 await page.click("a", modifiers=["Shift"])564 popup = await page_info.value565 assert await popup.opener() is None566@pytest.mark.only_browser("chromium")567async def test_page_event_should_work_with_ctrl_clicking(context, server, is_mac):568 # Firefox: reports an opener in this case.569 # WebKit: Ctrl+Click does not open a new tab.570 page = await context.new_page()571 await page.goto(server.EMPTY_PAGE)572 await page.set_content('<a href="/one-style.html">yo</a>')573 async with context.expect_page() as popup_info:574 await page.click("a", modifiers=["Meta" if is_mac else "Control"])575 popup = await popup_info.value...

Full Screen

Full Screen

test.py

Source:test.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import os3import shlex4import shutil5import subprocess6import tempfile7from itertools import zip_longest8from pathlib import Path9import nose.plugins.skip10import PyPDF211# TODO: rst2pdf currently does some crazy magic with extensions and globals12# that mean everything must be completely reloaded for each test to keep them13# isolated. The easiest way at the moment is to simply call the executable14# rather than try to load `rst2pdf.main`, but this will need to change once15# the handling of globals is fixed.16def pdf_pages(pdf):17 """18 Open a PDF file and yield each page as a temporary PDF file.19 """20 with pdf.open('rb') as fh:21 reader = PyPDF2.PdfFileReader(fh)22 for pagenum in range(reader.getNumPages()):23 page = reader.getPage(pagenum)24 writer = PyPDF2.PdfFileWriter()25 writer.addPage(page)26 with tempfile.NamedTemporaryFile(suffix='.pdf') as tmp:27 writer.write(tmp)28 tmp.flush()29 yield tmp30def compare_files(got, expect):31 """32 Compare two pdfs page by page and determine percentage difference.33 Pages are compared pixel by pixel using ImageMagick's ``convert``. If the34 total percentage difference is greater than ``threshold``, the test fails.35 If the number of pages differs, the test also fails.36 """37 got_pages = pdf_pages(got)38 expect_pages = pdf_pages(expect)39 iterpages = zip_longest(got_pages, expect_pages)40 error_pages = []41 for pagenum, (got_page, expect_page) in enumerate(iterpages):42 assert None not in (got_page, expect_page), 'EOF at page %d' % pagenum43 diff_page = got.parent / ('diff_%d.png' % (pagenum + 1))44 args = [45 'compare',46 got_page.name,47 expect_page.name,48 '-metric',49 'AE',50 str(diff_page)51 ]52 match_code = subprocess.call(args, stderr=subprocess.DEVNULL)53 if match_code != 0:54 error_pages.append(pagenum + 1)55 assert len(error_pages) == 0, \56 'Page match error on pages {}'.format(str(error_pages))57def build_sphinx(path):58 sphinx_path = path / 'sphinx'59 os.chdir(str(sphinx_path))60 env = os.environ.copy()61 env['SPHINXOPTS'] = '-Q'62 proc = subprocess.Popen(63 ['make', 'clean', 'pdf'],64 cwd=str(sphinx_path),65 env=env,66 stdout=subprocess.PIPE,67 stderr=subprocess.PIPE68 )69 try:70 out, err = proc.communicate(5)71 except subprocess.TimeoutExpired:72 print('-----> STDOUT')73 print(out)74 print('-----> STDERR')75 print(err)76 raise77 pdfs = list(sphinx_path.glob('_build/pdf/*.pdf'))78 if len(pdfs) > 1:79 (path / 'output.pdf').mkdir()80 for pdf in pdfs:81 shutil.copy(str(pdf), str(path / 'output.pdf'))82 return proc.returncode83def build_txt(path):84 os.chdir(str(path))85 inpfname = path / 'input.txt'86 style = path / 'input.style'87 cli = path / 'input.cli'88 outname = path / 'output.pdf'89 args = ['rst2pdf', '--date-invariant', '-v', str(inpfname), '-o', str(outname)]90 if cli.is_file():91 with cli.open('r') as f:92 args += shlex.split(f.read())93 if style.is_file():94 args += ['-s', str(style)]95 proc = subprocess.Popen(96 args,97 stdout=subprocess.PIPE,98 stderr=subprocess.PIPE99 )100 try:101 out, err = proc.communicate(5)102 except subprocess.TimeoutExpired:103 print('-----> STDOUT')104 print(out)105 print('-----> STDERR')106 print(err)107 raise108 return proc.returncode109class RunTest:110 def __init__(self, path):111 self.path = path112 self.description = path.name113 def __call__(self):114 if (self.path / 'ignore').exists():115 raise nose.plugins.skip.SkipTest116 use_sphinx = self.path.stem.startswith('sphinx')117 if use_sphinx:118 errcode = build_sphinx(self.path)119 else:120 errcode = build_txt(self.path)121 assert errcode == 0122 self.compare()123 def compare(self):124 got = self.path / 'output.pdf'125 expect = self.path / 'expected_output.pdf'126 if got.is_dir():127 for gotpdf in got.iterdir():128 expectpdf = expect / gotpdf.name129 assert expectpdf.exists()130 compare_files(gotpdf, expectpdf)131 else:132 compare_files(got, expect)133def test_files():134 """135 Runs all PDF tests136 """137 root = Path(__file__).parent / 'testcases'138 # Clean old files. Don't do this as part of teardown, because they will139 # probably be useful for post-mortems.140 for f in root.glob('*/output.pdf'):141 if f.is_dir():142 shutil.rmtree(str(f))143 else:144 f.unlink()145 for f in root.glob('*/diff*.png'):146 f.unlink()147 for d in root.glob('*/sphinx/_build'):148 shutil.rmtree(str(d))149 tests = sorted((d for d in root.iterdir() if d.is_dir()),150 key=lambda p: p.name)151 for path in tests:...

Full Screen

Full Screen

run_main.py

Source:run_main.py Github

copy

Full Screen

...27 handle_value = self.data.get_handle_value(i)28 # 预期步骤29 expect_handle = self.data.get_expect_handle(i)30 # 预期元素的界面31 expect_page = self.data.get_expect_page(i)32 # 预期元素33 expect_element = self.data.get_expect_element(i)34 # 运行开关35 switch_value = self.data.get_is_run(i)36 # 备注信息37 # tips = self.data.get_tips(i)38 # if handle_step == 'input':39 # # 输入40 # if handle_element == None:41 # print('操作元素为空。使用‘input’方法时,必须输入操作元素')42 # return None43 # elif handle_value == None:44 # print('操作值为空。使用‘input’方法时,必须输入操作值')45 # return None...

Full Screen

Full Screen

ifeng_video_common.py

Source:ifeng_video_common.py Github

copy

Full Screen

1# @Time : 2016/11/21 12:152# @Author : lixintong3from keywords import keyword, get_field, call, get_solo4from instrument import get_view5tab_view_pos = {6 '首页': 0,7 '直播': 1,8 '订阅': 2,9 '我的': 310}11page_name_ui_controller = {'点播底页': 'com.ifeng.newvideo.videoplayer.activity.ActivityVideoPlayerDetail',12 '自媒体': 'com.ifeng.newvideo.ui.subscribe.WeMediaHomePageActivity',13 '登录': 'com.ifeng.newvideo.login.activity.LoginMainActivity',14 '专辑底页': 'com.ifeng.newvideo.videoplayer.activity.ActivityTopicPlayer'15 }16@keyword("check_current_page")17def check_current_page(page_name):18 """19 功能:判断当前是否为某页20 :param player_type:"自媒体" 、"登录"、"点播底页"21 :return:22 """23 solo = get_solo()24 expect_page = page_name_ui_controller[page_name]25 current_activity = solo.get_current_activity()26 result = expect_page == current_activity.class_name27 assert result, "非{}页面".format(page_name)28@keyword("get_current_progress")29def get_current_progress(index=0):30 """31 功能:获取s播放器播放进度32 :param index:"0"33 :return:34 """35 seekbar_id = "com.ifeng.newvideo:id/control_seekBar"36 solo = get_solo()37 view = solo.get_view(res_id=seekbar_id, index=index)38 mSeekBarView = get_field(view, "mSeekBarView")39 progress = call(mSeekBarView, "getProgress")40 return progress41@keyword("check_video_state")42def check_video_state(state):43 """44 功能 检查播放器状态45 :param state: "playing"、"pause"46 :return:47 """48 solo = get_solo()49 video_skin = solo.get_view("com.ifeng.newvideo:id/video_skin")50 description = call(video_skin, "getContentDescription")51 assert description == state, "视频状态非{}".format(state)52@keyword("switch_tab")53def switch_tab(tab_name):54 """55 切换栏目56 :param tab_name:"首页"、"直播"、""订阅、"我的"57 :return:58 """59 solo = get_solo()60 tab_view = get_view("android:id/tabs")61 view = call(tab_view, "getChildTabViewAt", tab_view_pos[tab_name])62 solo.click_on_view(view)63@keyword("drag_progress_bar")64def drag_progress_bar(view, start_x, end_x, step_count):65 solo = get_solo()66 solo.drag_in_view(view, start_x, 50, end_x, 50, step_count)67@keyword("check_player_type")68def check_player_type(player_type):69 """70 确定当前播放器类型71 :param player_type: video 视频播放器;audio 音频播放器72 :return:73 """74 solo = get_solo()75 video_skin = solo.get_view("com.ifeng.newvideo:id/video_skin")76 description = call(video_skin, "getContentDescription")...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful