How to use __recalculate_selector method in SeleniumBase

Best Python code snippet using SeleniumBase

base_case.py

Source:base_case.py Github

copy

Full Screen

...26 if not timeout:27 timeout = settings.SMALL_TIMEOUT28 original_selector = selector29 original_by = by30 selector, by = self.__recalculate_selector(selector, by)31 if delay and (type(delay) in [int, float]) and delay > 0:32 time.sleep(delay)33 if self.__is_shadow_selector(selector):34 self.__shadow_click(selector)35 return36 element = page_actions.wait_for_element_visible(self.driver, selector, by, timeout=timeout)37 if scroll:38 self.__scroll_to_element(element, selector, by)39 element.click()40 def tap(self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None, delay=0):41 self.__check_scope()42 if not timeout:43 timeout = settings.SMALL_TIMEOUT44 selector, by = self.__recalculate_selector(selector, by)45 if delay and (type(delay) in [int, float]) and delay > 0:46 time.sleep(delay)47 element = page_actions.wait_for_element_visible(self.driver, selector, by, timeout=timeout)48 actions = TouchAction(self.driver)49 actions.tap(element).perform()50 def back(self):51 self.driver.back()52 def close(self):53 self.driver.close_app()54 def launch(self):55 self.driver.launch_app()56 def swipe_between_element(self, start_selector, dest_selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None):57 self.__check_scope()58 if not timeout:59 timeout = settings.SMALL_TIMEOUT60 start_selector, by = self.__recalculate_selector(start_selector, by)61 dest_selector, by = self.__recalculate_selector(dest_selector, by)62 start_element = page_actions.wait_for_element_visible(self.driver, start_selector, by, timeout=timeout)63 dest_element = page_actions.wait_for_element_visible(self.driver, dest_selector, by, timeout=timeout)64 self.driver.scroll(start_element,dest_element)65 def swipe_to_element(self, selector, by=MobileBy.ACCESSIBILITY_ID, start_x=100, start_y=100, end_x=0, end_y=0, duration=0, count=10, timeout=None):66 self.__check_scope()67 if not timeout:68 timeout = settings.SMALL_TIMEOUT69 selector, by = self.__recalculate_selector(selector, by)70 for i in range(count):71 try:72 self.is_element_visible(selector,by)73 break74 except Exception as e:75 self.driver.swipe(start_x, start_y, end_x, end_y, duration)76 def tap_by_coordinates(self, x, y):77 self.__check_scope()78 time.sleep(2)79 actions = TouchAction(self.driver)80 actions.tap(x=x, y=y).perform()81 def double_tap(self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None, delay=0):82 self.__check_scope()83 if not timeout:84 timeout = settings.SMALL_TIMEOUT85 selector, by = self.__recalculate_selector(selector, by)86 if delay and (type(delay) in [int, float]) and delay > 0:87 time.sleep(delay)88 element = page_actions.wait_for_element_visible(self.driver, selector, by, timeout=timeout)89 actions = TouchAction(self.driver)90 actions.tap(element, count=2).perform()91 def scroll_to_element(self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None):92 self.scroll_to(selector, by=by, timeout=timeout)93 def scroll_to(self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None):94 """ Fast scroll to destination """95 self.__check_scope()96 if not timeout:97 timeout = settings.SMALL_TIMEOUT98 element = self.wait_for_element_visible(99 selector, by=by, timeout=timeout100 )101 try:102 self.__scroll_to_element(element, selector, by)103 except (StaleElementReferenceException, ENI_Exception):104 time.sleep(0.12)105 element = self.wait_for_element_visible(106 selector, by=by, timeout=timeout107 )108 self.__scroll_to_element(element, selector, by)109 def __recalculate_selector(self, selector, by, xp_ok=True):110 """Use autodetection to return the correct selector with "by" updated.111 If "xp_ok" is False, don't call convert_css_to_xpath(), which is112 used to make the ":contains()" selector valid outside JS calls."""113 _type = type(selector) # First make sure the selector is a string114 not_string = False115 if sys.version_info[0] < 3:116 if _type is not str and _type is not unicode: # noqa: F821117 not_string = True118 else:119 if _type is not str:120 not_string = True121 if not_string:122 msg = "Expecting a selector of type: \"<class 'str'>\" (string)!"123 raise Exception('Invalid selector type: "%s"\n%s' % (_type, msg))124 if page_utils.is_xpath_selector(selector):125 by = MobileBy.XPATH126 if page_utils.is_link_text_selector(selector):127 selector = page_utils.get_link_text_from_selector(selector)128 by = MobileBy.LINK_TEXT129 if page_utils.is_partial_link_text_selector(selector):130 selector = page_utils.get_partial_link_text_from_selector(selector)131 by = MobileBy.PARTIAL_LINK_TEXT132 if page_utils.is_name_selector(selector):133 name = page_utils.get_name_from_selector(selector)134 selector = '[name="%s"]' % name135 by = MobileBy.CSS_SELECTOR136 if page_utils.is_id_selector(selector):137 by = MobileBy.ID138 return (selector, by)139 def __is_shadow_selector(self, selector):140 self.__fail_if_invalid_shadow_selector_usage(selector)141 if "::shadow " in selector:142 return True143 return False144 def __fail_if_invalid_shadow_selector_usage(self, selector):145 if selector.strip().endswith("::shadow"):146 msg = (147 "A Shadow DOM selector cannot end on a shadow root element!"148 " End the selector with an element inside the shadow root!"149 )150 raise Exception(msg)151 def double_click(self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None):152 from selenium.webdriver.common.action_chains import ActionChains153 self.__check_scope()154 if not timeout:155 timeout = settings.SMALL_TIMEOUT156 original_selector = selector157 original_by = by158 selector, by = self.__recalculate_selector(selector, by)159 element = page_actions.wait_for_element_visible(160 self.driver, selector, by, timeout=timeout161 )162 # Find the element one more time in case scrolling hid it163 element = page_actions.wait_for_element_visible(164 self.driver, selector, by, timeout=timeout165 )166 actions = ActionChains(self.driver)167 actions.double_click(element).perform()168 def go_back(self):169 self.__check_scope()170 self.__last_page_load_url = None171 self.driver.back()172 def scroll_screen(self, start_x=100, start_y=100, end_x=0, end_y=0, duration=0):173 """Swipe from one point to another point, for an optional duration.174 Args:175 start_x: x-coordinate at which to start176 start_y: y-coordinate at which to start177 end_x: x-coordinate at which to stop178 end_y: y-coordinate at which to stop179 duration: time to take the swipe, in ms.180 """181 self.driver.swipe(start_x, start_y, end_x, end_y, duration)182 def is_checked(self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None):183 """Determines if a checkbox or a radio button element is checked.184 Returns True if the element is checked.185 Returns False if the element is not checked.186 If the element is not present on the page, raises an exception.187 If the element is not a checkbox or radio, raises an exception."""188 self.__check_scope()189 if not timeout:190 timeout = settings.SMALL_TIMEOUT191 selector, by = self.__recalculate_selector(selector, by)192 kind = self.get_attribute(selector, "type", by=by, timeout=timeout)193 if kind != "checkbox" and kind != "radio":194 raise Exception("Expecting a checkbox or a radio button element!")195 is_checked = self.get_attribute(196 selector, "checked", by=by, timeout=timeout, hard_fail=False197 )198 if is_checked:199 return True200 else: # (NoneType)201 return False202 def __select_option(203 self,204 dropdown_selector,205 option,206 dropdown_by=MobileBy.ACCESSIBILITY_ID,207 option_by="text",208 timeout=None,209 ):210 """Selects an HTML <select> option by specification.211 Option specifications are by "text", "index", or "value".212 Defaults to "text" if option_by is unspecified or unknown."""213 from selenium.webdriver.support.ui import Select214 self.__check_scope()215 if not timeout:216 timeout = settings.SMALL_TIMEOUT217 dropdown_selector, dropdown_by = self.__recalculate_selector(218 dropdown_selector, dropdown_by219 )220 element = self.wait_for_element_present(221 dropdown_selector, by=dropdown_by, timeout=timeout222 )223 try:224 if option_by == "index":225 Select(element).select_by_index(option)226 elif option_by == "value":227 Select(element).select_by_value(option)228 else:229 Select(element).select_by_visible_text(option)230 except (StaleElementReferenceException, ENI_Exception):231 time.sleep(0.14)232 element = self.wait_for_element_present(233 dropdown_selector, by=dropdown_by, timeout=timeout234 )235 if option_by == "index":236 Select(element).select_by_index(option)237 elif option_by == "value":238 Select(element).select_by_value(option)239 else:240 Select(element).select_by_visible_text(option)241 def select_option_by_text(242 self,243 dropdown_selector,244 option,245 dropdown_by=MobileBy.ACCESSIBILITY_ID,246 timeout=None,247 ):248 """Selects an HTML <select> option by option text.249 @Params250 dropdown_selector - the <select> selector.251 option - the text of the option.252 """253 self.__check_scope()254 if not timeout:255 timeout = settings.SMALL_TIMEOUT256 self.__select_option(257 dropdown_selector,258 option,259 dropdown_by=dropdown_by,260 option_by="text",261 timeout=timeout,262 )263 def select_option_by_index(264 self,265 dropdown_selector,266 option,267 dropdown_by=MobileBy.ACCESSIBILITY_ID,268 timeout=None,269 ):270 """Selects an HTML <select> option by option index.271 @Params272 dropdown_selector - the <select> selector.273 option - the index number of the option.274 """275 self.__check_scope()276 if not timeout:277 timeout = settings.SMALL_TIMEOUT278 self.__select_option(279 dropdown_selector,280 option,281 dropdown_by=dropdown_by,282 option_by="index",283 timeout=timeout,284 )285 def select_option_by_value(286 self,287 dropdown_selector,288 option,289 dropdown_by=MobileBy.ACCESSIBILITY_ID,290 timeout=None,291 ):292 """Selects an HTML <select> option by option value.293 @Params294 dropdown_selector - the <select> selector.295 option - the value property of the option.296 """297 self.__check_scope()298 if not timeout:299 timeout = settings.SMALL_TIMEOUT300 self.__select_option(301 dropdown_selector,302 option,303 dropdown_by=dropdown_by,304 option_by="value",305 timeout=timeout,306 )307 def save_screenshot(self, name, folder=None):308 """Saves a screenshot of the current page.309 If no folder is specified, uses the folder where pytest was called.310 The screenshot will be in PNG format."""311 return page_actions.save_screenshot(self.driver, name, folder)312 def sleep(self, seconds):313 self.__check_scope()314 time.sleep(seconds)315 if seconds <= 0.3:316 time.sleep(seconds)317 else:318 start_ms = time.time() * 1000.0319 stop_ms = start_ms + (seconds * 1000.0)320 for x in range(int(seconds * 5)):321 now_ms = time.time() * 1000.0322 if now_ms >= stop_ms:323 break324 time.sleep(0.2)325 def is_selected(self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None):326 """ Same as is_checked() """327 return self.is_checked(selector, by=by, timeout=timeout)328 def check_if_unchecked(self, selector, by=MobileBy.ACCESSIBILITY_ID):329 """ If a checkbox or radio button is not checked, will check it. """330 self.__check_scope()331 selector, by = self.__recalculate_selector(selector, by)332 if not self.is_checked(selector, by=by):333 if self.is_element_visible(selector, by=by):334 self.click(selector, by=by)335 def select_if_unselected(self, selector, by=MobileBy.ACCESSIBILITY_ID):336 """ Same as check_if_unchecked() """337 self.check_if_unchecked(selector, by=by)338 def uncheck_if_checked(self, selector, by=MobileBy.ACCESSIBILITY_ID):339 """ If a checkbox is checked, will uncheck it. """340 self.__check_scope()341 selector, by = self.__recalculate_selector(selector, by)342 if self.is_checked(selector, by=by):343 if self.is_element_visible(selector, by=by):344 self.click(selector, by=by)345 def unselect_if_selected(self, selector, by=MobileBy.ACCESSIBILITY_ID):346 """ Same as uncheck_if_checked() """347 self.uncheck_if_checked(selector, by=by)348 def is_element_visible(self, selector, by=MobileBy.ACCESSIBILITY_ID):349 selector, by = self.__recalculate_selector(selector, by)350 return page_actions.is_element_visible(self.driver, selector, by)351 def get_attribute(352 self,353 selector,354 attribute,355 by=MobileBy.ACCESSIBILITY_ID,356 timeout=None,357 hard_fail=True,358 ):359 """ This method uses JavaScript to get the value of an attribute. """360 self.__check_scope()361 if not timeout:362 timeout = settings.SMALL_TIMEOUT363 selector, by = self.__recalculate_selector(selector, by)364 time.sleep(0.01)365 element = page_actions.wait_for_element_present(366 self.driver, selector, by, timeout367 )368 try:369 attribute_value = element.get_attribute(attribute)370 except (StaleElementReferenceException, ENI_Exception):371 time.sleep(0.14)372 element = page_actions.wait_for_element_present(373 self.driver, selector, by, timeout374 )375 attribute_value = element.get_attribute(attribute)376 if attribute_value is not None:377 return attribute_value378 else:379 if hard_fail:380 raise Exception(381 "Element {%s} has no attribute {%s}!"382 % (selector, attribute)383 )384 else:385 return None386 def __shadow_click(self, selector):387 element = self.__get_shadow_element(selector)388 element.click()389 def __get_shadow_element(self, selector, timeout=None):390 if timeout is None:391 timeout = settings.SMALL_TIMEOUT392 elif timeout == 0:393 timeout = 0.1 # Use for: is_shadow_element_* (* = present/visible)394 self.__fail_if_invalid_shadow_selector_usage(selector)395 if "::shadow " not in selector:396 raise Exception(397 'A Shadow DOM selector must contain at least one "::shadow "!'398 )399 selectors = selector.split("::shadow ")400 element = self.get_element(selectors[0])401 selector_chain = selectors[0]402 for selector_part in selectors[1:]:403 shadow_root = self.execute_script(404 "return arguments[0].shadowRoot", element405 )406 if timeout == 0.1 and not shadow_root:407 raise Exception(408 "Element {%s} has no shadow root!" % selector_chain409 )410 elif not shadow_root:411 time.sleep(2) # Wait two seconds for the shadow root to appear412 shadow_root = self.execute_script(413 "return arguments[0].shadowRoot", element414 )415 if not shadow_root:416 raise Exception(417 "Element {%s} has no shadow root!" % selector_chain418 )419 selector_chain += "::shadow "420 selector_chain += selector_part421 try:422 element = page_actions.wait_for_element_present(423 shadow_root,424 selector_part,425 by=MobileBy.CSS_SELECTOR,426 timeout=timeout,427 )428 except Exception:429 msg = (430 "Shadow DOM Element {%s} was not present after %s seconds!"431 % (selector_chain, timeout)432 )433 page_actions.timeout_exception("NoSuchElementException", msg)434 return element435 def execute_script(self, script, *args, **kwargs):436 self.__check_scope()437 return self.driver.execute_script(script, *args, **kwargs)438 def get_element(self, selector, by=MobileBy.CSS_SELECTOR, timeout=None):439 """Same as wait_for_element_present() - returns the element.440 The element does not need be visible (it may be hidden)."""441 self.__check_scope()442 if not timeout:443 timeout = settings.SMALL_TIMEOUT444 selector, by = self.__recalculate_selector(selector, by)445 return self.wait_for_element_present(selector, by=by, timeout=timeout)446 def wait_for_element_visible(447 self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None448 ):449 """ Same as self.wait_for_element() """450 self.__check_scope()451 if not timeout:452 timeout = settings.LARGE_TIMEOUT453 selector, by = self.__recalculate_selector(selector, by)454 if self.__is_shadow_selector(selector):455 return self.__wait_for_shadow_element_visible(selector)456 return page_actions.wait_for_element_visible(457 self.driver, selector, by, timeout458 )459 def wait_for_element_present(460 self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None461 ):462 """Waits for an element to appear in the HTML of a page.463 The element does not need be visible (it may be hidden)."""464 self.__check_scope()465 if not timeout:466 timeout = settings.LARGE_TIMEOUT467 selector, by = self.__recalculate_selector(selector, by)468 if self.__is_shadow_selector(selector):469 return self.__wait_for_shadow_element_present(selector)470 return page_actions.wait_for_element_present(471 self.driver, selector, by, timeout472 )473 def wait_for_element(self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None):474 """Waits for an element to appear in the HTML of a page.475 The element must be visible (it cannot be hidden)."""476 self.__check_scope()477 if not timeout:478 timeout = settings.LARGE_TIMEOUT479 selector, by = self.__recalculate_selector(selector, by)480 if self.__is_shadow_selector(selector):481 return self.__wait_for_shadow_element_visible(selector)482 return page_actions.wait_for_element_visible(483 self.driver, selector, by, timeout484 )485 def __wait_for_shadow_element_present(self, selector):486 element = self.__get_shadow_element(selector)487 return element488 def __wait_for_shadow_element_visible(self, selector):489 element = self.__get_shadow_element(selector)490 if not element.is_displayed():491 msg = "Shadow DOM Element {%s} was not visible!" % selector492 page_actions.timeout_exception("NoSuchElementException", msg)493 return element494 def __get_shadow_text(self, selector):495 element = self.__get_shadow_element(selector)496 return element.text497 def __wait_for_shadow_text_visible(self, text, selector):498 start_ms = time.time() * 1000.0499 stop_ms = start_ms + (settings.SMALL_TIMEOUT * 1000.0)500 for x in range(int(settings.SMALL_TIMEOUT * 10)):501 try:502 actual_text = self.__get_shadow_text(selector).strip()503 text = text.strip()504 if text not in actual_text:505 msg = (506 "Expected text {%s} in element {%s} was not visible!"507 % (text, selector)508 )509 page_actions.timeout_exception(510 "ElementNotVisibleException", msg511 )512 return True513 except Exception:514 now_ms = time.time() * 1000.0515 if now_ms >= stop_ms:516 break517 time.sleep(0.1)518 actual_text = self.__get_shadow_text(selector).strip()519 text = text.strip()520 if text not in actual_text:521 msg = "Expected text {%s} in element {%s} was not visible!" % (522 text,523 selector,524 )525 page_actions.timeout_exception("ElementNotVisibleException", msg)526 return True527 def find_elements(self, selector, by=MobileBy.ACCESSIBILITY_ID, limit=0):528 """Returns a list of matching WebElements.529 Elements could be either hidden or visible on the page.530 If "limit" is set and > 0, will only return that many elements."""531 selector, by = self.__recalculate_selector(selector, by)532 time.sleep(0.05)533 elements = self.driver.find_elements(by=by, value=selector)534 if limit and limit > 0 and len(elements) > limit:535 elements = elements[:limit]536 return elements537 def wait_for_element_not_present(538 self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None539 ):540 """Same as self.wait_for_element_absent()541 Waits for an element to no longer appear in the HTML of a page.542 A hidden element still counts as appearing in the page HTML.543 If waiting for elements to be hidden instead of nonexistent,544 use wait_for_element_not_visible() instead.545 """546 self.__check_scope()547 if not timeout:548 timeout = settings.LARGE_TIMEOUT549 selector, by = self.__recalculate_selector(selector, by)550 return page_actions.wait_for_element_absent(551 self.driver, selector, by, timeout552 )553 def find_visible_elements(self, selector, by=MobileBy.ACCESSIBILITY_ID, limit=0):554 """Returns a list of matching WebElements that are visible.555 If "limit" is set and > 0, will only return that many elements."""556 selector, by = self.__recalculate_selector(selector, by)557 time.sleep(0.05)558 v_elems = page_actions.find_visible_elements(self.driver, selector, by)559 if limit and limit > 0 and len(v_elems) > limit:560 v_elems = v_elems[:limit]561 return v_elems562 def click_visible_elements(563 self, selector, by=MobileBy.ACCESSIBILITY_ID, limit=0, timeout=None564 ):565 """Finds all matching page elements and clicks visible ones in order.566 If a click reloads or opens a new page, the clicking will stop.567 If no matching elements appear, an Exception will be raised.568 If "limit" is set and > 0, will only click that many elements.569 Also clicks elements that become visible from previous clicks.570 Works best for actions such as clicking all checkboxes on a page.571 Example: self.click_visible_elements('input[type="checkbox"]')"""572 self.__check_scope()573 if not timeout:574 timeout = settings.SMALL_TIMEOUT575 selector, by = self.__recalculate_selector(selector, by)576 self.wait_for_element_present(selector, by=by, timeout=timeout)577 elements = self.find_elements(selector, by=by)578 click_count = 0579 for element in elements:580 if limit and limit > 0 and click_count >= limit:581 return582 try:583 if element.is_displayed():584 self.__scroll_to_element(element)585 element.click()586 click_count += 1587 except ECI_Exception:588 continue # ElementClickInterceptedException (Overlay likel)589 except (StaleElementReferenceException, ENI_Exception):590 time.sleep(0.12)591 try:592 if element.is_displayed():593 self.__scroll_to_element(element)594 element.click()595 click_count += 1596 except (StaleElementReferenceException, ENI_Exception):597 return # Probably on new page / Elements are all stale598 def assert_true(self, expr, msg=None):599 """Asserts that the expression is True.600 Will raise an exception if the statement if False."""601 self.assertTrue(expr, msg=msg)602 def assert_false(self, expr, msg=None):603 """Asserts that the expression is False.604 Will raise an exception if the statement if True."""605 self.assertFalse(expr, msg=msg)606 def assert_equal(self, first, second, msg=None):607 """Asserts that the two values are equal.608 Will raise an exception if the values are not equal."""609 self.assertEqual(first, second, msg=msg)610 def assert_not_equal(self, first, second, msg=None):611 """Asserts that the two values are not equal.612 Will raise an exception if the values are equal."""613 self.assertNotEqual(first, second, msg=msg)614 def assert_in(self, first, second, msg=None):615 """Asserts that the first string is in the second string.616 Will raise an exception if the first string is not in the second."""617 self.assertIn(first, second, msg=msg)618 def assert_not_in(self, first, second, msg=None):619 """Asserts that the first string is not in the second string.620 Will raise an exception if the first string is in the second string."""621 self.assertNotIn(first, second, msg=msg)622 def assert_raises(self, *args, **kwargs):623 """Asserts that the following block of code raises an exception.624 Will raise an exception if the block of code has no exception.625 Usage Example =>626 # Verify that the expected exception is raised.627 with self.assert_raises(Exception):628 raise Exception("Expected Exception!")629 """630 return self.assertRaises(*args, **kwargs)631 def click_if_visible(self, selector, by=MobileBy.ACCESSIBILITY_ID):632 """If the page selector exists and is visible, clicks on the element.633 This method only clicks on the first matching element found.634 (Use click_visible_elements() to click all matching elements.)"""635 if self.is_element_visible(selector, by=by):636 self.click(selector, by=by)637 def __check_scope(self):638 if not self.__called_setup:639 self.setup()640 if hasattr(self, "device"): # self.browser stores the type of browser641 return # All good: setUp() already initialized variables in "self"642 else:643 from appiumbase.common.exceptions import OutOfScopeException644 message = (645 "\n It looks like you are trying to call a AppiumBase method"646 "\n from outside the scope of your test class's `self` object,"647 "\n which is initialized by calling BaseCase's setUp() method."648 "\n The `self` object is where all test variables are defined."649 "\n If you created a custom setUp() method (that overrided the"650 "\n the default one), make sure to call super().setUp() in it."651 "\n When using page objects, be sure to pass the `self` object"652 "\n from your test class into your page object methods so that"653 "\n they can call BaseCase class methods with all the required"654 "\n variables, which are initialized during the setUp() method"655 "\n that runs automatically before all tests called by pytest."656 )657 raise OutOfScopeException(message)658 def __scroll_to_element(self, element, selector, by):659 pass660 def slow_scroll_to(self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None):661 """ Slow motion scroll to destination """662 self.__check_scope()663 pass664 def slow_scroll_to_element(self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None):665 self.slow_scroll_to(selector, by=by, timeout=timeout)666 def set_text(self, selector, text, by=MobileBy.ACCESSIBILITY_ID, timeout=None):667 """Same as self.js_update_text()668 JavaScript + send_keys are used to update a text field.669 Performs self.set_value() and triggers event listeners.670 If text ends in "\n", set_value() presses RETURN after.671 Works faster than send_keys() alone due to the JS call.672 If not an input or textarea, sets textContent instead."""673 self.__check_scope()674 if not timeout:675 timeout = settings.LARGE_TIMEOUT676 selector, by = self.__recalculate_selector(selector, by)677 element = page_actions.wait_for_element_present(678 self.driver, selector, by, timeout679 )680 element.send_keys(text)681 def update_text(682 self, selector, text, by=MobileBy.ACCESSIBILITY_ID, timeout=None, retry=False683 ):684 """This method updates an element's text field with new text.685 Has multiple parts:686 * Waits for the element to be visible.687 * Waits for the element to be interactive.688 * Clears the text field.689 * Types in the new text.690 * Hits Enter/Submit (if the text ends in "\n").691 @Params692 selector - the selector of the text field693 text - the new text to type into the text field694 by - the type of selector to search by (Default: CSS Selector)695 timeout - how long to wait for the selector to be visible696 retry - if True, use JS if the Selenium text update fails697 """698 self.__check_scope()699 if not timeout:700 timeout = settings.LARGE_TIMEOUT701 selector, by = self.__recalculate_selector(selector, by)702 if self.__is_shadow_selector(selector):703 self.__shadow_type(selector, text)704 return705 element = self.wait_for_element_visible(706 selector, by=by, timeout=timeout707 )708 self.__scroll_to_element(element, selector, by)709 try:710 element.clear() # May need https://stackoverflow.com/a/50691625711 backspaces = Keys.BACK_SPACE * 42 # Is the answer to everything712 element.send_keys(backspaces) # In case autocomplete keeps text713 except (StaleElementReferenceException, ENI_Exception):714 time.sleep(0.16)715 element = self.wait_for_element_visible(716 selector, by=by, timeout=timeout717 )718 try:719 element.clear()720 except Exception:721 pass # Clearing the text field first might not be necessary722 except Exception:723 pass # Clearing the text field first might not be necessary724 if type(text) is int or type(text) is float:725 text = str(text)726 try:727 if not text.endswith("\n"):728 element.send_keys(text)729 else:730 element.send_keys(text[:-1])731 element.send_keys(Keys.RETURN)732 except (StaleElementReferenceException, ENI_Exception):733 time.sleep(0.16)734 element = self.wait_for_element_visible(735 selector, by=by, timeout=timeout736 )737 element.clear()738 if not text.endswith("\n"):739 element.send_keys(text)740 else:741 element.send_keys(text[:-1])742 element.send_keys(Keys.RETURN)743 except Exception:744 raise Exception()745 if self.slow_mode:746 self.__slow_mode_pause_if_active()747 def __slow_mode_pause_if_active(self):748 if self.slow_mode:749 wait_time = settings.DEFAULT_DEMO_MODE_TIMEOUT750 if self.demo_sleep:751 wait_time = float(self.demo_sleep)752 time.sleep(wait_time)753 def __get_test_id(self):754 """ The id used in various places such as the test log path. """755 test_id = "%s.%s.%s" % (756 self.__class__.__module__,757 self.__class__.__name__,758 self._testMethodName,759 )760 if self._sb_test_identifier and len(str(self._sb_test_identifier)) > 6:761 test_id = self._sb_test_identifier762 return test_id763 def set_time_limit(self, time_limit):764 self.__check_scope()765 if time_limit:766 try:767 ab_config.time_limit = float(time_limit)768 except Exception:769 ab_config.time_limit = None770 else:771 ab_config.time_limit = None772 if ab_config.time_limit and ab_config.time_limit > 0:773 ab_config.time_limit_ms = int(ab_config.time_limit * 1000.0)774 self.time_limit = ab_config.time_limit775 else:776 self.time_limit = None777 ab_config.time_limit = None778 ab_config.time_limit_ms = None779 def setup(self):780 if not hasattr(self, "_using_ab_fixture") and self.__called_setup:781 # This test already called setUp()782 return783 self.__called_setup = True784 self.__called_teardown = False785 self.is_pytest = None786 try:787 # This raises an exception if the test is not coming from pytest788 self.is_pytest = ab_config.is_pytest789 except Exception:790 # Not using pytest (probably nosetests)791 self.is_pytest = False792 if self.is_pytest:793 self.remote_address = "http://127.0.0.1:4723/wd/hub"794 self.device = ab_config.device795 self.data = ab_config.data796 self.var1 = ab_config.var1797 self.var2 = ab_config.var2798 self.var3 = ab_config.var3799 self.slow_mode = ab_config.slow_mode800 self.time_limit = ab_config._time_limit801 ab_config.time_limit = ab_config._time_limit802 self.environment = ab_config.environment803 self.env = self.environment # Add a shortened version804 self.mobile_emulator = ab_config.mobile_emulator805 self.cap_file = ab_config.cap_file806 self.settings_file = ab_config.settings_file807 self._reuse_session = ab_config.reuse_session808 self.browser_stack = ab_config.browser_stack809 self.lambda_test = ab_config.lambda_test810 self.pytest_html_report = ab_config.pytest_html_report811 if not hasattr(self, "device"):812 raise Exception(813 'AppiiumBase plugins DID NOT load! * Please REINSTALL!'814 )815 if self.settings_file:816 from appiumbase.core import settings_parser817 settings_parser.set_settings(self.settings_file)818 ab_config.start_time_ms = int(time.time() * 1000.0)819 # Configure the test time limit (if used).820 self.set_time_limit(self.time_limit)821 from appiumbase.core import capabilities_parser822 self.dc = capabilities_parser.get_desired_capabilities(self.cap_file)823 if self.browser_stack:824 self.remote_address = "http://hub-cloud.browserstack.com/wd/hub"825 if self.lambda_test:826 username = self.dc['user']827 accesskey = self.dc['accessKey']828 self.remote_address = f"https://{username}:{accesskey}@beta-hub.lambdatest.com/wd/hub"829 appium_launcher.start_appium_service()830 self.driver = webdriver.Remote(self.remote_address, self.dc)831 return self.driver832 def app_background(self, time):833 """834 put the app in background with given time(in seconds)835 example : app_background(10)836 """837 self.driver.background_app(time)838 def check_keyboard_shown(self):839 """840 Attempts to detect whether a software keyboard is present841 Returns:842 `True` if keyboard is shown843 """844 return self.driver.is_keyboard_shown()845 def get_location_of_element(self,selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None):846 location={}847 self.__check_scope()848 if not timeout:849 timeout = settings.LARGE_TIMEOUT850 selector, by = self.__recalculate_selector(selector, by)851 element = page_actions.wait_for_element_present(852 self.driver, selector, by, timeout853 )854 location = element.location_in_view855 x = location['x']856 y = location['y']857 return x , y858 def scroll_the_screen(self,x,y,a,b,d):859 '''860 Scroll the screen according to cordinates861 :param x: starting point 1862 :param y: starting point 2863 :param a: end point 1864 :param b: end point 2865 :param d: duration866 '''867 self.driver.swipe(x,y,a,b,d)868 def long_press_on_btn(self, selector, by=MobileBy.ACCESSIBILITY_ID, timeout=None, delay=0):869 '''870 self.__check_scope()871 time.sleep(2)872 actions = TouchAction(self.driver)873 actions.long_press(selector)874 '''875 self.__check_scope()876 if not timeout:877 timeout = settings.SMALL_TIMEOUT878 selector, by = self.__recalculate_selector(selector, by)879 if delay and (type(delay) in [int, float]) and delay > 0:880 time.sleep(delay)881 element = page_actions.wait_for_element_visible(self.driver, selector, by, timeout=timeout)882 actions = TouchAction(self.driver)883 actions.long_press(element).perform()884 def tearDown(self):885 """886 Be careful if a subclass of BaseCase overrides setUp()887 You'll need to add the following line to the subclass's tearDown():888 super(SubClassOfBaseCase, self).tearDown()889 """890 self.driver.quit()...

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 SeleniumBase 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