How to use parent_locator_str method in toolium

Best Python code snippet using toolium_python

page_element.py

Source:page_element.py Github

copy

Full Screen

...70 """71 try:72 self._find_web_element()73 except NoSuchElementException as exception:74 parent_msg = f" and parent locator {self.parent_locator_str()}" if self.parent else ''75 msg = "Page element of type '%s' with locator %s%s not found"76 self.logger.error(msg, type(self).__name__, self.locator, parent_msg)77 exception.msg += "\n {}".format(msg % (type(self).__name__, self.locator, parent_msg))78 raise exception79 return self._web_element80 def _find_web_element(self):81 """Find WebElement using element locator and save it in _web_element attribute"""82 if not self._web_element or not self.driver_wrapper.config.getboolean_optional('Driver', 'save_web_element'):83 # check context for mobile webviews84 if self.driver_wrapper.config.getboolean_optional('Driver', 'automatic_context_selection'):85 if self.driver_wrapper.is_android_test():86 self._android_automatic_context_selection()87 elif self.driver_wrapper.is_ios_test():88 self._ios_automatic_context_selection()89 # If the element is encapsulated we use the shadowroot tag in yaml (eg. Shadowroot: root_element_name)90 if self.shadowroot:91 if self.locator[0] != By.CSS_SELECTOR:92 raise Exception('Locator type should be CSS_SELECTOR using shadowroot but found: '93 '%s' % self.locator[0])94 # querySelector only support CSS SELECTOR locator95 self._web_element = self.driver.execute_script('return document.querySelector("%s").shadowRoot.'96 'querySelector("%s")' % (self.shadowroot,97 self.locator[1]))98 else:99 # Element will be searched from parent element or from driver100 base = self.utils.get_web_element(self.parent) if self.parent else self.driver101 # Find elements and get the correct index or find a single element102 self._web_element = base.find_elements(*self.locator)[self.order] if self.order \103 else base.find_element(*self.locator)104 def _android_automatic_context_selection(self):105 """Change context selection depending if the element is a webview for android devices"""106 # we choose the appPackage webview context, and select the first window returned by mobile: getContexts107 if self.webview:108 context = None109 window_handle = None110 if self.webview_context_selection_callback:111 context, window_handle = self.webview_context_selection_callback(*self.webview_csc_args)112 else:113 app_web_context = "{}_{}".format(PageElement.webview_context_prefix,114 self.driver.capabilities['appPackage'])115 contexts = self.driver.execute_script('mobile: getContexts')116 context_dict = next(117 (item for item in contexts if 'webviewName' in item and item['webviewName'] == app_web_context),118 None)119 if context_dict:120 context = app_web_context121 window_handle = 'CDwindow-{}'.format(context_dict['pages'][0]['id'])122 if context:123 if self.driver.context != context:124 self.driver.switch_to.context(context)125 if self.driver.current_window_handle != window_handle:126 self.driver.switch_to.window(window_handle)127 else:128 raise KeyError("WEBVIEW context not found")129 else:130 if self.driver.context != PageElement.native_context:131 self.driver.switch_to.context(PageElement.native_context)132 def _ios_automatic_context_selection(self):133 """Change context selection depending if the element is a webview for ios devices"""134 # we choose the last webview context returned by mobile: getContexts for the bundleid135 if self.webview:136 if self.webview_context_selection_callback:137 context_id = self.webview_context_selection_callback(*self.webview_csc_args)138 else:139 contexts = self.driver.execute_script('mobile: getContexts')140 context_id = next(141 (item['id'] for item in reversed(contexts) if142 'bundleId' in item and item['bundleId'] == self.driver.capabilities['bundleId']),143 None)144 if context_id:145 if self.driver.context != context_id:146 self.driver.switch_to.context(context_id)147 else:148 raise KeyError("WEBVIEW context not found")149 else:150 if self.driver.context != PageElement.native_context:151 self.driver.switch_to.context(PageElement.native_context)152 def parent_locator_str(self):153 """Return string with locator tuple for parent element154 :returns: parent element locator155 """156 if isinstance(self.parent, PageElement):157 parent_locator = str(self.parent.locator)158 elif isinstance(self.parent, tuple):159 parent_locator = str(self.parent)160 else:161 parent_locator = '[WebElement without locator]'162 return parent_locator163 def scroll_element_into_view(self):164 """Scroll element into view165 :returns: page element instance166 """167 x = self.web_element.location['x']168 y = self.web_element.location['y']169 self.driver.execute_script('window.scrollTo({0}, {1})'.format(x, y))170 return self171 def is_present(self):172 """Find element and return True if it is present173 :returns: True if element is located174 """175 try:176 # Use _find_web_element() instead of web_element to avoid logging error message177 self._web_element = None178 self._find_web_element()179 return True180 except NoSuchElementException:181 return False182 def is_visible(self):183 """Find element and return True if it is visible184 :returns: True if element is visible185 """186 return self.is_present() and self.web_element.is_displayed()187 def _wait_until_condition(self, condition, timeout=None):188 """Search element and wait until it meets the condition189 :param condition: name of condition that must meet the element (visible, not_visible, clickable)190 :param timeout: max time to wait191 :returns: page element instance192 """193 try:194 condition_msg = ''195 if condition == 'visible':196 condition_msg = 'not found or is not visible'197 self.utils.wait_until_element_visible(self, timeout)198 elif condition == 'not_visible':199 condition_msg = 'is still visible'200 self.utils.wait_until_element_not_visible(self, timeout)201 elif condition == 'clickable':202 condition_msg = 'not found or is not clickable'203 self.utils.wait_until_element_clickable(self, timeout)204 except TimeoutException as exception:205 parent_msg = f" and parent locator {self.parent_locator_str()}" if self.parent else ''206 timeout = timeout if timeout else self.utils.get_explicitly_wait()207 msg = "Page element of type '%s' with locator %s%s %s after %s seconds"208 msg = msg % (type(self).__name__, self.locator, parent_msg, condition_msg, timeout)209 self.logger.error(msg)210 exception.msg += "\n {}".format(msg)211 raise exception212 return self213 def wait_until_visible(self, timeout=None):214 """Search element and wait until it is visible215 :param timeout: max time to wait216 :returns: page element instance217 """218 return self._wait_until_condition('visible', timeout)219 def wait_until_not_visible(self, timeout=None):...

Full Screen

Full Screen

element_factory.py

Source:element_factory.py Github

copy

Full Screen

1import typing as ty2from selenium.webdriver.common.by import By3from selenium.webdriver.remote.webelement import WebElement4from core.elements.base_element_factory import BaseElementFactory5from core.elements.states.element_state import Displayed6from core.elements.states.element_count import ElementCount7from core.elements.base_parent_element import BaseParentElement8T = ty.TypeVar('T')9class ElementFactory(BaseElementFactory):10 """Factory that creates elements."""11 def get_custom_element(self, element_supplier: ty.Callable[[ty.Tuple[By, str], str,12 ty.Callable[[WebElement], bool]], T],13 locator: ty.Tuple[By, str], name: str,14 state: ty.Callable[[WebElement], bool] = Displayed) -> T:15 """16 Create custom element according to passed parameters.17 :param element_supplier: Delegate that defines constructor of element.18 :param locator: Locator of the target element.19 :param name: Name of the target element.20 :param state: State of the target element.21 :return: Instance of custom element.22 """23 return element_supplier(locator, name, state)24 def find_child_element(self, parent_element: BaseParentElement,25 element_supplier: ty.Callable[[ty.Tuple[By, str], str,26 ty.Callable[[WebElement], bool]], T],27 child_locator: ty.Tuple[By, str], name: str = str(),28 state: ty.Callable[[WebElement], bool] = Displayed) -> T:29 """30 Find child element by its locator relative to parent element.31 :param parent_element: Parent element.32 :param element_supplier: Callable object that defines constructor of element in case of custom element.33 :param child_locator: Locator of child element relative to its parent.34 :param name: Child element name.35 :param state: Child element state.36 :return: Instance of child element.37 """38 element_name = name if name else f"Child element of {parent_element.name}"39 locator = self._generate_absolute_child_locator(parent_element.locator, child_locator)40 return element_supplier(locator, element_name, state)41 def find_child_elements(self, parent_element: BaseParentElement,42 element_supplier: ty.Callable[[ty.Tuple[By, str], str,43 ty.Callable[[WebElement], bool]], T],44 child_locator: ty.Tuple[By, str], name: str = str(),45 state: ty.Callable[[WebElement], bool] = Displayed,46 expected_count: ElementCount = ElementCount.ANY.value) -> ty.List[T]:47 """48 Find child element by its locator relative to parent element.49 :param parent_element: Parent element.50 :param element_supplier: Callable object that defines constructor of element in case of custom element.51 :param child_locator: Locator of child element relative to its parent.52 :param name: Child element name.53 :param state: Child element state.54 :param expected_count: Expected number of elements that have to be found (zero, more than zero, any).55 :return: Instance of child element.56 """57 elements_name = name if name else f"Child element of {parent_element.name}"58 locator = self._generate_absolute_child_locator(parent_element.locator, child_locator)59 return self.find_elements(element_supplier, locator, elements_name, state, expected_count)60 def find_elements(self, element_supplier: ty.Callable[[ty.Tuple[By, str], str, ty.Callable[[WebElement], bool]], T],61 locator: ty.Tuple[By, str], name: str = str(), state: ty.Callable[[WebElement], bool] = Displayed,62 expected_count: ElementCount = ElementCount.ANY.value) -> ty.List[T]:63 """64 Find list of elements by base locator.65 :param element_supplier: Callable object that defines constructor of element in case of custom element.66 :param locator: Base elements locator.67 :param name: Elements name.68 :param state: Elements state.69 :param expected_count: Expected number of elements that have to be found (zero, more than zero, any).70 :return: List of elements that found by locator.71 """72 self.__check_elements_count(locator, state, expected_count)73 web_elements = self._element_finder.find_elements(locator, state, 0)74 found_elements = []75 for element_index in range(1, len(web_elements) + 1):76 element_locator = self._generate_xpath_locator(locator, element_index)77 element_name = f"{name if name else 'element'} {element_index}"78 found_elements.append(element_supplier(element_locator, element_name, state))79 return found_elements80 def __check_elements_count(self, locator: ty.Tuple[By, str], state: ty.Callable[[WebElement], bool] = Displayed,81 expected_count: ElementCount = ElementCount.ANY.value) -> None:82 if expected_count == ElementCount.ZERO:83 self._conditional_wait.wait_for_true(84 lambda: not any(85 self._element_finder.find_elements(locator, state, 0)86 ),87 message=self._localization_manager.get_localized_message(88 "loc.elements.found.but.should.not", locator, "desired"89 ),90 )91 elif expected_count == ElementCount.MORE_THAN_ZERO:92 self._conditional_wait.wait_for_true(93 lambda: any(94 self._element_finder.find_elements(locator, state, 0)95 ),96 message=self._localization_manager.get_localized_message(97 "loc.no.elements.found.by.locator", locator98 ),99 )100 elif expected_count == ElementCount.ANY:101 self._conditional_wait.wait_for(102 lambda: self._element_finder.find_elements(locator, state, 0) is not None103 )104 else:105 raise ValueError(f"No such expected value: {expected_count}")106 def _generate_absolute_child_locator(self, parent_locator: ty.Tuple[By, str], child_locator: ty.Tuple[By, str]) \107 -> ty.Tuple[By, str]:108 if self._is_locator_supported_for_xpath_extraction(109 parent_locator110 ) and self._is_locator_supported_for_xpath_extraction(child_locator):111 parent_locator_str = self._extract_xpath_from_locator(parent_locator)112 child_locator_str = self._extract_xpath_from_locator(child_locator)113 cropped_child_locator_str = (114 child_locator_str[1:]115 if child_locator_str.startswith(".")116 else child_locator_str117 )118 return By.XPATH, parent_locator_str + cropped_child_locator_str119 else:120 raise ValueError(121 f"Locator types {parent_locator} and {child_locator} not supported for building absolute locator"122 )123 def _generate_xpath_locator(self, base_locator: ty.Tuple[By, str], element_index: int) -> ty.Tuple[By, str]:124 if self._is_locator_supported_for_xpath_extraction(base_locator):125 return (126 By.XPATH,127 f"({self._extract_xpath_from_locator(base_locator)})[{element_index}]",128 )129 else:130 raise ValueError(131 f"Multiple elements' base_locator type {base_locator} is not supported yet"132 )133 @staticmethod134 def _is_locator_supported_for_xpath_extraction(locator: ty.Tuple[By, str]) -> bool:135 return locator[0] in [By.XPATH, By.TAG_NAME]136 @staticmethod137 def _extract_xpath_from_locator(locator: ty.Tuple[By, str]) -> str:138 locator_type = locator[0]139 locator_value = locator[1]140 locators_map = {By.XPATH: locator_value, By.TAG_NAME: f"//{locator_value}"}141 if locator_type not in locators_map:142 ValueError(143 f"Cannot define xpath from locator {locator_value}. Locator type {locator_type} is not supported yet."144 )...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run toolium 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