How to use _with_element method in Playwright Python

Best Python code snippet using playwright-python

DeltaGenerator.py

Source:DeltaGenerator.py Github

copy

Full Screen

...60 @_wraps_with_cleaned_sig(method, 1) # Remove self from sig.61 def wrapped_method(self, *args, **kwargs):62 return method(self, *args, **kwargs)63 return wrapped_method64def _with_element(method):65 """Wrap function and pass a NewElement proto to be filled.66 This is a function decorator.67 Converts a method of the with arguments (self, element, ...) into a method68 with arguments (self, ...). Thus, the instantiation of the element proto69 object and creation of the element are handled automatically.70 Parameters71 ----------72 method : callable73 A DeltaGenerator method with arguments (self, element, ...)74 Returns75 -------76 callable77 A new DeltaGenerator method with arguments (self, ...)78 """...

Full Screen

Full Screen

caching.py

Source:caching.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# Copyright 2018-2019 Streamlit Inc.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""A library of caching utilities."""16# Python 2/3 compatibility17from __future__ import absolute_import, division, print_function18import ast19import contextlib20import hashlib21import inspect22import os23import shutil24import struct25import textwrap26import threading27from collections import namedtuple28from functools import wraps29import streamlit as st30from streamlit import config, util31from streamlit.compatibility import setup_2_3_shims32from streamlit.hashing import CodeHasher, Context, get_hash33from streamlit.logger import get_logger34setup_2_3_shims(globals())35CACHED_ST_FUNCTION_WARNING = """36Your script writes to your Streamlit app from within a cached function. This37code will only be called when we detect a cache "miss", which can lead to38unexpected results.39How to resolve this warning:40* Move the streamlit function call outside the cached function.41* Or, if you know what you're doing, use `@st.cache(suppress_st_warning=True)`42to suppress the warning.43"""44try:45 # cPickle, if available, is much faster than pickle.46 # Source: https://pymotw.com/2/pickle/47 import cPickle as pickle48except ImportError:49 import pickle50LOGGER = get_logger(__name__)51class CacheError(Exception):52 pass53class CacheKeyNotFoundError(Exception):54 pass55class CachedObjectWasMutatedError(ValueError):56 pass57CacheEntry = namedtuple("CacheEntry", ["value", "hash", "args_mutated"])58DiskCacheEntry = namedtuple("DiskCacheEntry", ["value", "args_mutated"])59# The in memory cache.60_mem_cache = {} # type: Dict[string, CacheEntry]61# A thread-local counter that's incremented when we enter @st.cache62# and decremented when we exit.63class ThreadLocalCacheInfo(threading.local):64 def __init__(self):65 self.within_cached_func = 066 self.suppress_st_function_warning = 067_cache_info = ThreadLocalCacheInfo()68@contextlib.contextmanager69def _calling_cached_function():70 _cache_info.within_cached_func += 171 try:72 yield73 finally:74 _cache_info.within_cached_func -= 175@contextlib.contextmanager76def suppress_cached_st_function_warning():77 _cache_info.suppress_st_function_warning += 178 try:79 yield80 finally:81 _cache_info.suppress_st_function_warning -= 182 assert _cache_info.suppress_st_function_warning >= 083def _show_cached_st_function_warning(dg):84 # Avoid infinite recursion by suppressing additional cached85 # function warnings from within the cached function warning.86 with suppress_cached_st_function_warning():87 dg.warning(CACHED_ST_FUNCTION_WARNING)88def maybe_show_cached_st_function_warning(dg):89 """If appropriate, warn about calling st.foo inside @cache.90 DeltaGenerator's @_with_element and @_widget wrappers use this to warn91 the user when they're calling st.foo() from within a function that is92 wrapped in @st.cache.93 Parameters94 ----------95 dg : DeltaGenerator96 The DeltaGenerator to publish the warning to.97 """98 if (99 _cache_info.within_cached_func > 0100 and _cache_info.suppress_st_function_warning <= 0101 ):102 _show_cached_st_function_warning(dg)103class _AddCopy(ast.NodeTransformer):104 """105 An AST transformer that wraps function calls with copy.deepcopy.106 Use this transformer if you will convert the AST back to code.107 The code won't work without importing copy.108 """109 def __init__(self, func_name):110 self.func_name = func_name111 def visit_Call(self, node):112 if (113 hasattr(node.func, "func")114 and hasattr(node.func.func, "value")115 and node.func.func.value.id == "st"116 and node.func.func.attr == "cache"117 ):118 # Wrap st.cache(func(...))().119 return ast.copy_location(120 ast.Call(121 func=ast.Attribute(122 value=ast.Name(id="copy", ctx=ast.Load()),123 attr="deepcopy",124 ctx=ast.Load(),125 ),126 args=[node],127 keywords=[],128 ),129 node,130 )131 elif hasattr(node.func, "id") and node.func.id == self.func_name:132 # Wrap func(...) where func is the cached function.133 # Add caching to nested calls.134 self.generic_visit(node)135 return ast.copy_location(136 ast.Call(137 func=ast.Attribute(138 value=ast.Name(id="copy", ctx=ast.Load()),139 attr="deepcopy",140 ctx=ast.Load(),141 ),142 args=[node],143 keywords=[],144 ),145 node,146 )147 self.generic_visit(node)148 return node149def _build_caching_func_error_message(persisted, func, caller_frame):150 name = func.__name__151 frameinfo = inspect.getframeinfo(caller_frame)152 caller_file_name, caller_lineno, _, lines, _ = frameinfo153 try:154 import astor155 # only works if calling code is a single line156 parsed_context = ast.parse(lines[0].lstrip())157 parsed_context = _AddCopy(name).visit(parsed_context)158 copy_code = astor.to_source(parsed_context)159 except SyntaxError:160 LOGGER.debug("Could not parse calling code `%s`.", lines[0])161 copy_code = "... = copy.deepcopy(%s(...))" % name162 if persisted:163 load_or_rerun = "loading the value back from the disk cache"164 else:165 load_or_rerun = "rerunning the function"166 message = textwrap.dedent(167 """168 **Your code mutated a cached return value**169 Streamlit detected the mutation of a return value of `{name}`, which is170 a cached function. This happened in `{file_name}` line {lineno}. Since171 `persist` is `{persisted}`, Streamlit will make up for this by172 {load_or_rerun}, so your code will still work, but with reduced173 performance.174 To dismiss this warning, try one of the following:175 1. *Preferred:* fix the code by removing the mutation. The simplest way176 to do this is to copy the cached value to a new variable, which you are177 allowed to mutate. For example, try changing `{caller_file_name}` line178 {caller_lineno} to:179 ```python180 import copy181 {copy_code}182 ```183 2. Add `ignore_hash=True` to the `@streamlit.cache` decorator for184 `{name}`. This is an escape hatch for advanced users who really know185 what they're doing.186 Learn more about caching and copying in the [Streamlit documentation]187 (https://streamlit.io/docs/tutorial/create_a_data_explorer_app.html).188 """189 ).strip("\n")190 return message.format(191 name=name,192 load_or_rerun=load_or_rerun,193 file_name=os.path.relpath(func.__code__.co_filename),194 lineno=func.__code__.co_firstlineno,195 persisted=persisted,196 caller_file_name=os.path.relpath(caller_file_name),197 caller_lineno=caller_lineno,198 copy_code=copy_code,199 )200def _build_caching_block_error_message(persisted, code, line_number_range):201 if persisted:202 load_or_rerun = "loading the value back from the disk cache"203 else:204 load_or_rerun = "rerunning the code"205 [start, end] = line_number_range206 if start == end:207 lines = "line {start}".format(start=start)208 else:209 lines = "lines {start} to {end}".format(start=start, end=end)210 message = textwrap.dedent(211 """212 **Your code mutated a cached value**213 Streamlit detected the mutation of a cached value in `{file_name}` in214 {lines}. Since `persist` is `{persisted}`, Streamlit will make up for215 this by {load_or_rerun}, so your code will still work, but with reduced216 performance.217 To dismiss this warning, try one of the following:218 1. *Preferred:* fix the code by removing the mutation. The simplest way219 to do this is to copy the cached value to a new variable, which you are220 allowed to mutate.221 2. Add `ignore_hash=True` to the constructor of `streamlit.Cache`. This222 is an escape hatch for advanced users who really know what they're223 doing.224 Learn more about caching and copying in the [Streamlit documentation]225 (https://streamlit.io/docs/tutorial/create_a_data_explorer_app.html).226 """227 ).strip("\n")228 return message.format(229 load_or_rerun=load_or_rerun,230 file_name=os.path.relpath(code.co_filename),231 lines=lines,232 persisted=persisted,233 )234def _build_args_mutated_message(func):235 message = textwrap.dedent(236 """237 **Cached function mutated its input arguments**238 When decorating a function with `@st.cache`, the arguments should not239 be mutated inside the function body, as that breaks the caching240 mechanism. Please update the code of `{name}` to bypass the mutation.241 See the [Streamlit242 docs](https://streamlit.io/docs/tutorial/create_a_data_explorer_app.html) for more243 info.244 """245 ).strip("\n")246 return message.format(name=func.__name__)247def _read_from_mem_cache(key, ignore_hash):248 if key in _mem_cache:249 entry = _mem_cache[key]250 if ignore_hash or get_hash(entry.value) == entry.hash:251 LOGGER.debug("Memory cache HIT: %s", type(entry.value))252 return entry.value, entry.args_mutated253 else:254 LOGGER.debug("Cache object was mutated: %s", key)255 raise CachedObjectWasMutatedError()256 else:257 LOGGER.debug("Memory cache MISS: %s", key)258 raise CacheKeyNotFoundError("Key not found in mem cache")259def _write_to_mem_cache(key, value, ignore_hash, args_mutated):260 _mem_cache[key] = CacheEntry(261 value=value,262 hash=None if ignore_hash else get_hash(value),263 args_mutated=args_mutated,264 )265def _read_from_disk_cache(key):266 path = util.get_streamlit_file_path("cache", "%s.pickle" % key)267 try:268 with util.streamlit_read(path, binary=True) as input:269 value, args_mutated = pickle.load(input)270 LOGGER.debug("Disk cache HIT: %s", type(value))271 except util.Error as e:272 LOGGER.error(e)273 raise CacheError("Unable to read from cache: %s" % e)274 except (OSError, FileNotFoundError): # Python 2 # Python 3275 raise CacheKeyNotFoundError("Key not found in disk cache")276 return value, args_mutated277def _write_to_disk_cache(key, value, args_mutated):278 path = util.get_streamlit_file_path("cache", "%s.pickle" % key)279 try:280 with util.streamlit_write(path, binary=True) as output:281 entry = DiskCacheEntry(value=value, args_mutated=args_mutated)282 pickle.dump(entry, output, pickle.HIGHEST_PROTOCOL)283 # In python 2, it's pickle struct error.284 # In python 3, it's an open error in util.285 except (util.Error, struct.error) as e:286 LOGGER.debug(e)287 # Clean up file so we don't leave zero byte files.288 try:289 os.remove(path)290 except (FileNotFoundError, IOError, OSError):291 pass292 raise CacheError("Unable to write to cache: %s" % e)293def _read_from_cache(key, persisted, ignore_hash, func_or_code, message_opts):294 """295 Read the value from the cache. Our goal is to read from memory296 if possible. If the data was mutated (hash changed), we show a297 warning. If reading from memory fails, we either read from disk298 or rerun the code.299 """300 try:301 return _read_from_mem_cache(key, ignore_hash)302 except (CacheKeyNotFoundError, CachedObjectWasMutatedError) as e:303 if isinstance(e, CachedObjectWasMutatedError):304 if inspect.isroutine(func_or_code):305 message = _build_caching_func_error_message(306 persisted, func_or_code, message_opts307 )308 else:309 message = _build_caching_block_error_message(310 persisted, func_or_code, message_opts311 )312 st.warning(message)313 if persisted:314 value, args_mutated = _read_from_disk_cache(key)315 _write_to_mem_cache(key, value, ignore_hash, args_mutated)316 return value, args_mutated317 raise e318def _write_to_cache(key, value, persist, ignore_hash, args_mutated):319 _write_to_mem_cache(key, value, ignore_hash, args_mutated)320 if persist:321 _write_to_disk_cache(key, value, args_mutated)322def cache(323 func=None,324 persist=False,325 ignore_hash=False,326 show_spinner=True,327 suppress_st_warning=False,328):329 """Function decorator to memoize function executions.330 Parameters331 ----------332 func : callable333 The function to cache. Streamlit hashes the function and dependent code.334 Streamlit can only hash nested objects (e.g. `bar` in `foo.bar`) in335 Python 3.4+.336 persist : boolean337 Whether to persist the cache on disk.338 ignore_hash : boolean339 Disable hashing return values. These hash values are otherwise340 used to validate that return values are not mutated.341 show_spinner : boolean342 Enable the spinner. Default is True to show a spinner when there is343 a cache miss.344 suppress_st_warning : boolean345 Suppress warnings about calling Streamlit functions from within346 the cached function.347 Example348 -------349 >>> @st.cache350 ... def fetch_and_clean_data(url):351 ... # Fetch data from URL here, and then clean it up.352 ... return data353 ...354 >>> d1 = fetch_and_clean_data(DATA_URL_1)355 >>> # Actually executes the function, since this is the first time it was356 >>> # encountered.357 >>>358 >>> d2 = fetch_and_clean_data(DATA_URL_1)359 >>> # Does not execute the function. Just returns its previously computed360 >>> # value. This means that now the data in d1 is the same as in d2.361 >>>362 >>> d3 = fetch_and_clean_data(DATA_URL_2)363 >>> # This is a different URL, so the function executes.364 To set the `persist` parameter, use this command as follows:365 >>> @st.cache(persist=True)366 ... def fetch_and_clean_data(url):367 ... # Fetch data from URL here, and then clean it up.368 ... return data369 To disable hashing return values, set the `ignore_hash` parameter to `True`:370 >>> @st.cache(ignore_hash=True)371 ... def fetch_and_clean_data(url):372 ... # Fetch data from URL here, and then clean it up.373 ... return data374 """375 # Support passing the params via function decorator, e.g.376 # @st.cache(persist=True, ignore_hash=True)377 if func is None:378 return lambda f: cache(379 func=f,380 persist=persist,381 ignore_hash=ignore_hash,382 show_spinner=show_spinner,383 suppress_st_warning=suppress_st_warning,384 )385 @wraps(func)386 def wrapped_func(*args, **kwargs):387 """This function wrapper will only call the underlying function in388 the case of a cache miss. Cached objects are stored in the cache/389 directory."""390 if not config.get_option("client.caching"):391 LOGGER.debug("Purposefully skipping cache")392 return func(*args, **kwargs)393 name = func.__name__394 if len(args) == 0 and len(kwargs) == 0:395 message = "Running %s()." % name396 else:397 message = "Running %s(...)." % name398 def get_or_set_cache():399 hasher = hashlib.new("md5")400 args_hasher = CodeHasher("md5", hasher)401 args_hasher.update([args, kwargs])402 LOGGER.debug("Hashing arguments to %s of %i bytes.", name, args_hasher.size)403 args_digest_before = args_hasher.digest()404 code_hasher = CodeHasher("md5", hasher)405 code_hasher.update(func)406 LOGGER.debug("Hashing function %s in %i bytes.", name, code_hasher.size)407 key = hasher.hexdigest()408 LOGGER.debug("Cache key: %s", key)409 caller_frame = inspect.currentframe().f_back410 try:411 return_value, args_mutated = _read_from_cache(412 key, persist, ignore_hash, func, caller_frame413 )414 except (CacheKeyNotFoundError, CachedObjectWasMutatedError):415 with _calling_cached_function():416 if suppress_st_warning:417 with suppress_cached_st_function_warning():418 return_value = func(*args, **kwargs)419 else:420 return_value = func(*args, **kwargs)421 args_hasher_after = CodeHasher("md5")422 args_hasher_after.update([args, kwargs])423 args_mutated = args_digest_before != args_hasher_after.digest()424 _write_to_cache(key, return_value, persist, ignore_hash, args_mutated)425 if args_mutated:426 # If we're inside a _nested_ cached function, our427 # _within_cached_function_counter will be non-zero.428 # Suppress the warning about this.429 with suppress_cached_st_function_warning():430 st.warning(_build_args_mutated_message(func))431 return return_value432 if show_spinner:433 with st.spinner(message):434 return get_or_set_cache()435 else:436 return get_or_set_cache()437 # Make this a well-behaved decorator by preserving important function438 # attributes.439 try:440 wrapped_func.__dict__.update(func.__dict__)441 except AttributeError:442 pass443 return wrapped_func444class Cache(dict):445 """Cache object to persist data across reruns.446 Parameters447 ----------448 Example449 -------450 >>> c = st.Cache()451 ... if c:452 ... # Fetch data from URL here, and then clean it up. Finally assign to c.453 ... c.data = ...454 ...455 >>> # c.data will always be defined but the code block only runs the first time456 The only valid side effect inside the if code block are changes to c. Any457 other side effect has undefined behavior.458 In Python 3.8 and above, you can combine the assignment and if-check with an459 assignment expression (`:=`).460 >>> if c := st.Cache():461 ... # Fetch data from URL here, and then clean it up. Finally assign to c.462 ... c.data = ...463 """464 def __init__(self, persist=False, ignore_hash=False):465 self._persist = persist466 self._ignore_hash = ignore_hash467 dict.__init__(self)468 def has_changes(self):469 current_frame = inspect.currentframe()470 caller_frame = current_frame.f_back471 current_file = inspect.getfile(current_frame)472 caller_file = inspect.getfile(caller_frame)473 real_caller_is_parent_frame = current_file == caller_file474 if real_caller_is_parent_frame:475 caller_frame = caller_frame.f_back476 frameinfo = inspect.getframeinfo(caller_frame)477 filename, caller_lineno, _, code_context, _ = frameinfo478 code_context = code_context[0]479 context_indent = len(code_context) - len(code_context.lstrip())480 lines = []481 # TODO: Memoize open(filename, 'r') in a way that clears the memoized version with each482 # run of the user's script. Then use the memoized text here, in st.echo, and other places.483 with open(filename, "r") as f:484 for line in f.readlines()[caller_lineno:]:485 if line.strip() == "":486 lines.append(line)487 indent = len(line) - len(line.lstrip())488 if indent <= context_indent:489 break490 if line.strip() and not line.lstrip().startswith("#"):491 lines.append(line)492 while lines[-1].strip() == "":493 lines.pop()494 code_block = "".join(lines)495 program = textwrap.dedent(code_block)496 context = Context(dict(caller_frame.f_globals, **caller_frame.f_locals), {}, {})497 code = compile(program, filename, "exec")498 code_hasher = CodeHasher("md5")499 code_hasher.update(code, context)500 LOGGER.debug("Hashing block in %i bytes.", code_hasher.size)501 key = code_hasher.hexdigest()502 LOGGER.debug("Cache key: %s", key)503 try:504 value, _ = _read_from_cache(505 key,506 self._persist,507 self._ignore_hash,508 code,509 [caller_lineno + 1, caller_lineno + len(lines)],510 )511 self.update(value)512 except (CacheKeyNotFoundError, CachedObjectWasMutatedError):513 if self._ignore_hash and not self._persist:514 # If we don't hash the results, we don't need to use exec and just return True.515 # This way line numbers will be correct.516 _write_to_cache(key, self, False, True, None)517 return True518 exec(code, caller_frame.f_globals, caller_frame.f_locals)519 _write_to_cache(key, self, self._persist, self._ignore_hash, None)520 # Return False so that we have control over the execution.521 return False522 def __bool__(self):523 return self.has_changes()524 # Python 2 doesn't have __bool__525 def __nonzero__(self):526 return self.has_changes()527 def __getattr__(self, key):528 if key not in self:529 raise AttributeError("Cache has no atribute %s" % key)530 return self.__getitem__(key)531 def __setattr__(self, key, value):532 dict.__setitem__(self, key, value)533def clear_cache():534 """Clear the memoization cache.535 Returns536 -------537 boolean538 True if the disk cache was cleared. False otherwise (e.g. cache file539 doesn't exist on disk).540 """541 _clear_mem_cache()542 return _clear_disk_cache()543def get_cache_path():544 return util.get_streamlit_file_path("cache")545def _clear_disk_cache():546 # TODO: Only delete disk cache for functions related to the user's current547 # script.548 cache_path = get_cache_path()549 if os.path.isdir(cache_path):550 shutil.rmtree(cache_path)551 return True552 return False553def _clear_mem_cache():554 global _mem_cache...

Full Screen

Full Screen

_locator.py

Source:_locator.py Github

copy

Full Screen

...77 raise Error('Inner "has" locator must belong to the same frame.')78 self._selector += " >> has=" + json.dumps(has._selector)79 def __repr__(self) -> str:80 return f"<Locator frame={self._frame!r} selector={self._selector!r}>"81 async def _with_element(82 self,83 task: Callable[[ElementHandle, float], Awaitable[T]],84 timeout: float = None,85 ) -> T:86 timeout = self._frame.page._timeout_settings.timeout(timeout)87 deadline = (monotonic_time() + timeout) if timeout else 088 handle = await self.element_handle(timeout=timeout)89 if not handle:90 raise Error(f"Could not resolve {self._selector} to DOM Element")91 try:92 return await task(93 handle,94 (deadline - monotonic_time()) if deadline else 0,95 )96 finally:97 await handle.dispose()98 @property99 def page(self) -> "Page":100 return self._frame.page101 async def bounding_box(self, timeout: float = None) -> Optional[FloatRect]:102 return await self._with_element(103 lambda h, _: h.bounding_box(),104 timeout,105 )106 async def check(107 self,108 position: Position = None,109 timeout: float = None,110 force: bool = None,111 noWaitAfter: bool = None,112 trial: bool = None,113 ) -> None:114 params = locals_to_params(locals())115 return await self._frame.check(self._selector, strict=True, **params)116 async def click(117 self,118 modifiers: List[KeyboardModifier] = None,119 position: Position = None,120 delay: float = None,121 button: MouseButton = None,122 clickCount: int = None,123 timeout: float = None,124 force: bool = None,125 noWaitAfter: bool = None,126 trial: bool = None,127 ) -> None:128 params = locals_to_params(locals())129 return await self._frame.click(self._selector, strict=True, **params)130 async def dblclick(131 self,132 modifiers: List[KeyboardModifier] = None,133 position: Position = None,134 delay: float = None,135 button: MouseButton = None,136 timeout: float = None,137 force: bool = None,138 noWaitAfter: bool = None,139 trial: bool = None,140 ) -> None:141 params = locals_to_params(locals())142 return await self._frame.dblclick(self._selector, strict=True, **params)143 async def dispatch_event(144 self,145 type: str,146 eventInit: Dict = None,147 timeout: float = None,148 ) -> None:149 params = locals_to_params(locals())150 return await self._frame.dispatch_event(self._selector, strict=True, **params)151 async def evaluate(152 self, expression: str, arg: Serializable = None, timeout: float = None153 ) -> Any:154 return await self._with_element(155 lambda h, _: h.evaluate(expression, arg),156 timeout,157 )158 async def evaluate_all(self, expression: str, arg: Serializable = None) -> Any:159 params = locals_to_params(locals())160 return await self._frame.eval_on_selector_all(self._selector, **params)161 async def evaluate_handle(162 self, expression: str, arg: Serializable = None, timeout: float = None163 ) -> "JSHandle":164 return await self._with_element(165 lambda h, o: h.evaluate_handle(expression, arg), timeout166 )167 async def fill(168 self,169 value: str,170 timeout: float = None,171 noWaitAfter: bool = None,172 force: bool = None,173 ) -> None:174 params = locals_to_params(locals())175 return await self._frame.fill(self._selector, strict=True, **params)176 def locator(177 self,178 selector: str,179 has_text: Union[str, Pattern] = None,180 has: "Locator" = None,181 ) -> "Locator":182 return Locator(183 self._frame,184 f"{self._selector} >> {selector}",185 has_text=has_text,186 has=has,187 )188 def frame_locator(self, selector: str) -> "FrameLocator":189 return FrameLocator(self._frame, self._selector + " >> " + selector)190 async def element_handle(191 self,192 timeout: float = None,193 ) -> ElementHandle:194 params = locals_to_params(locals())195 handle = await self._frame.wait_for_selector(196 self._selector, strict=True, state="attached", **params197 )198 assert handle199 return handle200 async def element_handles(self) -> List[ElementHandle]:201 return await self._frame.query_selector_all(self._selector)202 @property203 def first(self) -> "Locator":204 return Locator(self._frame, f"{self._selector} >> nth=0")205 @property206 def last(self) -> "Locator":207 return Locator(self._frame, f"{self._selector} >> nth=-1")208 def nth(self, index: int) -> "Locator":209 return Locator(self._frame, f"{self._selector} >> nth={index}")210 async def focus(self, timeout: float = None) -> None:211 params = locals_to_params(locals())212 return await self._frame.focus(self._selector, strict=True, **params)213 async def count(214 self,215 ) -> int:216 return await self._frame._query_count(self._selector)217 async def drag_to(218 self,219 target: "Locator",220 force: bool = None,221 noWaitAfter: bool = None,222 timeout: float = None,223 trial: bool = None,224 sourcePosition: Position = None,225 targetPosition: Position = None,226 ) -> None:227 params = locals_to_params(locals())228 del params["target"]229 return await self._frame.drag_and_drop(230 self._selector, target._selector, strict=True, **params231 )232 async def get_attribute(self, name: str, timeout: float = None) -> Optional[str]:233 params = locals_to_params(locals())234 return await self._frame.get_attribute(235 self._selector,236 strict=True,237 **params,238 )239 async def hover(240 self,241 modifiers: List[KeyboardModifier] = None,242 position: Position = None,243 timeout: float = None,244 force: bool = None,245 trial: bool = None,246 ) -> None:247 params = locals_to_params(locals())248 return await self._frame.hover(249 self._selector,250 strict=True,251 **params,252 )253 async def inner_html(self, timeout: float = None) -> str:254 params = locals_to_params(locals())255 return await self._frame.inner_html(256 self._selector,257 strict=True,258 **params,259 )260 async def inner_text(self, timeout: float = None) -> str:261 params = locals_to_params(locals())262 return await self._frame.inner_text(263 self._selector,264 strict=True,265 **params,266 )267 async def input_value(self, timeout: float = None) -> str:268 params = locals_to_params(locals())269 return await self._frame.input_value(270 self._selector,271 strict=True,272 **params,273 )274 async def is_checked(self, timeout: float = None) -> bool:275 params = locals_to_params(locals())276 return await self._frame.is_checked(277 self._selector,278 strict=True,279 **params,280 )281 async def is_disabled(self, timeout: float = None) -> bool:282 params = locals_to_params(locals())283 return await self._frame.is_disabled(284 self._selector,285 strict=True,286 **params,287 )288 async def is_editable(self, timeout: float = None) -> bool:289 params = locals_to_params(locals())290 return await self._frame.is_editable(291 self._selector,292 strict=True,293 **params,294 )295 async def is_enabled(self, timeout: float = None) -> bool:296 params = locals_to_params(locals())297 return await self._frame.is_editable(298 self._selector,299 strict=True,300 **params,301 )302 async def is_hidden(self, timeout: float = None) -> bool:303 params = locals_to_params(locals())304 return await self._frame.is_hidden(305 self._selector,306 strict=True,307 **params,308 )309 async def is_visible(self, timeout: float = None) -> bool:310 params = locals_to_params(locals())311 return await self._frame.is_visible(312 self._selector,313 strict=True,314 **params,315 )316 async def press(317 self,318 key: str,319 delay: float = None,320 timeout: float = None,321 noWaitAfter: bool = None,322 ) -> None:323 params = locals_to_params(locals())324 return await self._frame.press(self._selector, strict=True, **params)325 async def screenshot(326 self,327 timeout: float = None,328 type: Literal["jpeg", "png"] = None,329 path: Union[str, pathlib.Path] = None,330 quality: int = None,331 omitBackground: bool = None,332 animations: Literal["allow", "disabled"] = None,333 caret: Literal["hide", "initial"] = None,334 scale: Literal["css", "device"] = None,335 mask: List["Locator"] = None,336 ) -> bytes:337 params = locals_to_params(locals())338 return await self._with_element(339 lambda h, timeout: h.screenshot(timeout=timeout, **params)340 )341 async def scroll_into_view_if_needed(342 self,343 timeout: float = None,344 ) -> None:345 return await self._with_element(346 lambda h, timeout: h.scroll_into_view_if_needed(timeout=timeout),347 timeout,348 )349 async def select_option(350 self,351 value: Union[str, List[str]] = None,352 index: Union[int, List[int]] = None,353 label: Union[str, List[str]] = None,354 element: Union["ElementHandle", List["ElementHandle"]] = None,355 timeout: float = None,356 noWaitAfter: bool = None,357 force: bool = None,358 ) -> List[str]:359 params = locals_to_params(locals())360 return await self._frame.select_option(361 self._selector,362 strict=True,363 **params,364 )365 async def select_text(self, force: bool = None, timeout: float = None) -> None:366 params = locals_to_params(locals())367 return await self._with_element(368 lambda h, timeout: h.select_text(timeout=timeout, **params), timeout369 )370 async def set_input_files(371 self,372 files: Union[373 str,374 pathlib.Path,375 FilePayload,376 List[Union[str, pathlib.Path]],377 List[FilePayload],378 ],379 timeout: float = None,380 noWaitAfter: bool = None,381 ) -> None:...

Full Screen

Full Screen

delta_generator_test.py

Source:delta_generator_test.py Github

copy

Full Screen

...141 # Check cleaned output.142 dg = FakeDeltaGenerator()143 result = wrapped(dg, "foo", data="bar")144 self.assertEqual(result, ("foo", "bar"))145 def test_with_element(self):146 wrapped = _with_element(FakeDeltaGenerator.fake_text)147 dg = FakeDeltaGenerator()148 data = "some_text"149 # This would really look like st.text(data) but since we're150 # testng the wrapper, it looks like this.151 element = wrapped(dg, data)152 self.assertEqual(element.new_element.text.body, data)153 def test_with_element_exception(self):154 wrapped = _with_element(FakeDeltaGenerator.fake_text_raise_exception)155 dg = FakeDeltaGenerator()156 data = "some_text"157 with self.assertRaises(Exception) as ctx:158 wrapped(dg, data)159 self.assertTrue("Exception in fake_text_raise_exception" in str(ctx.exception))160 def set_widget_requires_args(self):161 st.text_input()162 c = self.get_delta_from_queue().new_element.exception163 self.assertEqual(c.type, "TypeError")164class DeltaGeneratorClassTest(testutil.DeltaGeneratorTestCase):165 """Test DeltaGenerator Class."""166 def setUp(self):167 super(DeltaGeneratorClassTest, self).setUp(override_root=False)168 def test_constructor(self):...

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