Best Python code snippet using playwright-python
test_page.py
Source:test_page.py
...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):...
_page.py
Source:_page.py
...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(...
test_browsercontext.py
Source:test_browsercontext.py
...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...
_browser_context.py
Source:_browser_context.py
...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 )...
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.
Get 100 minutes of automation test minutes FREE!!