How to use expose_binding method in Playwright Python

Best Python code snippet using playwright-python

test_page.py

Source:test_page.py Github

copy

Full Screen

...229 }"""230 )231 response = await response_info.value232 assert response.url == server.PREFIX + "/digits/2.png"233async def test_expose_binding(page):234 binding_source = []235 def binding(source, a, b):236 binding_source.append(source)237 return a + b238 await page.expose_binding("add", lambda source, a, b: binding(source, a, b))239 result = await page.evaluate("add(5, 6)")240 assert binding_source[0]["context"] == page.context241 assert binding_source[0]["page"] == page242 assert binding_source[0]["frame"] == page.main_frame243 assert result == 11244async def test_expose_function(page, server):245 await page.expose_function("compute", lambda a, b: a * b)246 result = await page.evaluate("compute(9, 4)")247 assert result == 36248@pytest.mark.skip("todo mxschmitt")249async def test_expose_function_should_throw_exception_in_page_context(page, server):250 def throw():251 raise Exception("WOOF WOOF")252 await page.expose_function("woof", lambda: throw())253 result = await page.evaluate(254 """async() => {255 try {256 await woof()257 } catch (e) {258 return {message: e.message, stack: e.stack}259 }260 }"""261 )262 assert result["message"] == "WOOF WOOF"263 assert __file__ in result["stack"]264async def test_expose_function_should_be_callable_from_inside_add_init_script(page):265 called = []266 await page.expose_function("woof", lambda: called.append(True))267 await page.add_init_script("woof()")268 await page.reload()269 assert called == [True]270async def test_expose_function_should_survive_navigation(page, server):271 await page.expose_function("compute", lambda a, b: a * b)272 await page.goto(server.EMPTY_PAGE)273 result = await page.evaluate("compute(9, 4)")274 assert result == 36275async def test_expose_function_should_await_returned_promise(page):276 async def mul(a, b):277 return a * b278 await page.expose_function("compute", mul)279 assert await page.evaluate("compute(3, 5)") == 15280async def test_expose_function_should_work_on_frames(page, server):281 await page.expose_function("compute", lambda a, b: a * b)282 await page.goto(server.PREFIX + "/frames/nested-frames.html")283 frame = page.frames[1]284 assert await frame.evaluate("compute(3, 5)") == 15285async def test_expose_function_should_work_on_frames_before_navigation(page, server):286 await page.goto(server.PREFIX + "/frames/nested-frames.html")287 await page.expose_function("compute", lambda a, b: a * b)288 frame = page.frames[1]289 assert await frame.evaluate("compute(3, 5)") == 15290async def test_expose_function_should_work_after_cross_origin_navigation(page, server):291 await page.goto(server.EMPTY_PAGE)292 await page.expose_function("compute", lambda a, b: a * b)293 await page.goto(server.CROSS_PROCESS_PREFIX + "/empty.html")294 assert await page.evaluate("compute(9, 4)") == 36295async def test_expose_function_should_work_with_complex_objects(page, server):296 await page.expose_function("complexObject", lambda a, b: dict(x=a["x"] + b["x"]))297 result = await page.evaluate("complexObject({x: 5}, {x: 2})")298 assert result["x"] == 7299async def test_expose_bindinghandle_should_work(page, server):300 targets = []301 def logme(t):302 targets.append(t)303 return 17304 await page.expose_binding("logme", lambda source, t: logme(t), handle=True)305 result = await page.evaluate("logme({ foo: 42 })")306 assert (await targets[0].evaluate("x => x.foo")) == 42307 assert result == 17308async def test_page_error_should_fire(page, server, is_webkit):309 async with page.expect_event("pageerror") as error_info:310 await page.goto(server.PREFIX + "/error.html")311 error = await error_info.value312 assert error.message == "Fancy error!"313 stack = await page.evaluate("window.e.stack")314 # Note that WebKit reports the stack of the 'throw' statement instead of the Error constructor call.315 if is_webkit:316 stack = stack.replace("14:25", "15:19")317 assert error.stack == stack318async def test_page_error_should_handle_odd_values(page, is_firefox):...

Full Screen

Full Screen

_page.py

Source:_page.py Github

copy

Full Screen

...367 self, url: str = None, path: Union[str, Path] = None, content: str = None368 ) -> ElementHandle:369 return await self._main_frame.add_style_tag(**locals_to_params(locals()))370 async def expose_function(self, name: str, callback: Callable) -> None:371 await self.expose_binding(name, lambda source, *args: callback(*args))372 async def expose_binding(373 self, name: str, callback: Callable, handle: bool = None374 ) -> None:375 if name in self._bindings:376 raise Error(f'Function "{name}" has been already registered')377 if name in self._browser_context._bindings:378 raise Error(379 f'Function "{name}" has been already registered in the browser context'380 )381 self._bindings[name] = callback382 await self._channel.send(383 "exposeBinding", dict(name=name, needsHandle=handle or False)384 )385 async def set_extra_http_headers(self, headers: Dict[str, str]) -> None:386 await self._channel.send(...

Full Screen

Full Screen

test_browsercontext.py

Source:test_browsercontext.py Github

copy

Full Screen

...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_frame...

Full Screen

Full Screen

_browser_context.py

Source:_browser_context.py Github

copy

Full Screen

...133 script = file.read()134 if not isinstance(script, str):135 raise Error("Either path or source parameter must be specified")136 await self._channel.send("addInitScript", dict(source=script))137 async def expose_binding(138 self, name: str, callback: Callable, handle: bool = None139 ) -> None:140 for page in self._pages:141 if name in page._bindings:142 raise Error(143 f'Function "{name}" has been already registered in one of the pages'144 )145 if name in self._bindings:146 raise Error(f'Function "{name}" has been already registered')147 self._bindings[name] = callback148 await self._channel.send(149 "exposeBinding", dict(name=name, needsHandle=handle or False)150 )151 async def expose_function(self, name: str, callback: Callable) -> None:152 await self.expose_binding(name, lambda source, *args: callback(*args))153 async def route(self, url: URLMatch, handler: RouteHandler) -> None:154 self._routes.append(RouteHandlerEntry(URLMatcher(url), handler))155 if len(self._routes) == 1:156 await self._channel.send(157 "setNetworkInterceptionEnabled", dict(enabled=True)158 )159 async def unroute(160 self, url: URLMatch, handler: Optional[RouteHandler] = None161 ) -> None:162 self._routes = list(163 filter(164 lambda r: r.matcher.match != url or (handler and r.handler != handler),165 self._routes,166 )...

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