How to use _element_find_by_text method in robotframework-appiumlibrary

Best Python code snippet using robotframework-appiumlibrary_python

_element.py

Source:_element.py Github

copy

Full Screen

...40 :param exact_match:41 :return: 元素的存在与预期相符时返回True,否则返回False42 """43 if textname:44 el = self._element_find_by_text(resourceId, textname, exact_match)45 if el and not isexist:46 self._warn("Exception: unexcepted element {}".format(textname))47 return None48 if not el and isexist:49 self._warn("Exception: text {} not found".format(textname))50 return None51 else:52 el = self._element_find(resourceId, True, True)53 if el and not isexist:54 self._warn("Exception: unexcepted element {}".format(resourceId))55 return None56 if not el and isexist:57 self._warn("Exception: element {} not found".format(resourceId))58 return None59 return True60 def click_button(self, index_or_name):61 """ Click button """62 _platform_class_dict = {'ios': 'UIAButton',63 'android': 'android.widget.Button'}64 if self._is_support_platform(_platform_class_dict):65 class_name = self._get_class(_platform_class_dict)66 self._click_element_by_class_name(class_name, index_or_name)67 def click_text(self, resourceId, text, exact_match=False):68 """Click text identified by ``text``.69 By default tries to click first text involves given ``text``, if you would70 like to click exactly matching text, then set ``exact_match`` to `True`.71 If there are multiple use of ``text`` and you do not want first one,72 use `locator` with `Get Web Elements` instead.73 """74 self._element_find_by_text(resourceId, text, exact_match).click()75 def input_text(self, locator, text):76 """Types the given `text` into text field identified by `locator`.77 See `introduction` for details about locating elements.78 """79 self._info("Typing text '%s' into text field '%s'" % (text, locator))80 self._element_input_text_by_locator(locator, text)81 def input_password(self, locator, text):82 """Types the given password into text field identified by `locator`.83 Difference between this keyword and `Input Text` is that this keyword84 does not log the given password. See `introduction` for details about85 locating elements.86 """87 self._info("Typing password into text field '%s'" % locator)88 self._element_input_text_by_locator(locator, text)89 def input_value(self, locator, text):90 """Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value91 See `introduction` for details about locating elements.92 """93 self._info("Setting text '%s' into text field '%s'" % (text, locator))94 self._element_input_value_by_locator(locator, text)95 def hide_keyboard(self, key_name=None):96 """Hides the software keyboard on the device. (optional) In iOS, use `key_name` to press97 a particular key, ex. `Done`. In Android, no parameters are used.98 """99 driver = self._current_application()100 driver.hide_keyboard(key_name)101 def page_should_contain_text(self, text, loglevel='INFO'):102 """Verifies that current page contains `text`.103 If this keyword fails, it automatically logs the page source104 using the log level specified with the optional `loglevel` argument.105 Giving `NONE` as level disables logging.106 """107 if not self._is_text_present(text):108 self.log_source(loglevel)109 raise AssertionError("Page should have contained text '%s' "110 "but did not" % text)111 self._info("Current page contains text '%s'." % text)112 def page_should_not_contain_text(self, text, loglevel='INFO'):113 """Verifies that current page not contains `text`.114 If this keyword fails, it automatically logs the page source115 using the log level specified with the optional `loglevel` argument.116 Giving `NONE` as level disables logging.117 """118 if self._is_text_present(text):119 self.log_source(loglevel)120 raise AssertionError("Page should not have contained text '%s'" % text)121 self._info("Current page does not contains text '%s'." % text)122 def page_should_contain_element(self, locator, loglevel='INFO'):123 """Verifies that current page contains `locator` element.124 If this keyword fails, it automatically logs the page source125 using the log level specified with the optional `loglevel` argument.126 Giving `NONE` as level disables logging.127 """128 if not self._is_element_present(locator):129 self.log_source(loglevel)130 raise AssertionError("Page should have contained element '%s' "131 "but did not" % locator)132 self._info("Current page contains element '%s'." % locator)133 def page_should_not_contain_element(self, locator, loglevel='INFO'):134 """Verifies that current page not contains `locator` element.135 If this keyword fails, it automatically logs the page source136 using the log level specified with the optional `loglevel` argument.137 Giving `NONE` as level disables logging.138 """139 if self._is_element_present(locator):140 self.log_source(loglevel)141 raise AssertionError("Page should not have contained element '%s'" % locator)142 self._info("Current page not contains element '%s'." % locator)143 def element_should_be_disabled(self, locator, loglevel='INFO'):144 """Verifies that element identified with locator is disabled.145 Key attributes for arbitrary elements are `id` and `name`. See146 `introduction` for details about locating elements.147 """148 if self._element_find(locator, True, True).is_enabled():149 self.log_source(loglevel)150 raise AssertionError("Element '%s' should be disabled "151 "but did not" % locator)152 self._info("Element '%s' is disabled ." % locator)153 def element_should_be_enabled(self, locator, loglevel='INFO'):154 """Verifies that element identified with locator is enabled.155 Key attributes for arbitrary elements are `id` and `name`. See156 `introduction` for details about locating elements.157 """158 if not self._element_find(locator, True, True).is_enabled():159 self.log_source(loglevel)160 raise AssertionError("Element '%s' should be enabled "161 "but did not" % locator)162 self._info("Element '%s' is enabled ." % locator)163 def element_should_be_visible(self, locator, loglevel='INFO'):164 """Verifies that element identified with locator is visible.165 Key attributes for arbitrary elements are `id` and `name`. See166 `introduction` for details about locating elements.167 New in ATXLibrary 1.4.5168 """169 if not self._element_find(locator, True, True).is_displayed():170 self.log_source(loglevel)171 raise AssertionError("Element '%s' should be visible "172 "but did not" % locator)173 def element_name_should_be(self, locator, expected):174 element = self._element_find(locator, True, True)175 if str(expected) != str(element.get_attribute('name')):176 raise AssertionError("Element '%s' name should be '%s' "177 "but it is '%s'." % (locator, expected, element.get_attribute('name')))178 self._info("Element '%s' name is '%s' " % (locator, expected))179 def element_value_should_be(self, locator, expected):180 element = self._element_find(locator, True, True)181 if str(expected) != str(element.get_attribute('value')):182 raise AssertionError("Element '%s' value should be '%s' "183 "but it is '%s'." % (locator, expected, element.get_attribute('value')))184 self._info("Element '%s' value is '%s' " % (locator, expected))185 def element_attribute_should_match(self, locator, attr_name, match_pattern, regexp=False):186 """Verify that an attribute of an element matches the expected criteria.187 The element is identified by _locator_. See `introduction` for details188 about locating elements. If more than one element matches, the first element is selected.189 The _attr_name_ is the name of the attribute within the selected element.190 The _match_pattern_ is used for the matching, if the match_pattern is191 - boolean or 'True'/'true'/'False'/'false' String then a boolean match is applied192 - any other string is cause a string match193 The _regexp_ defines whether the string match is done using regular expressions (i.e. BuiltIn Library's194 [http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Should%20Match%20Regexp|Should195 Match Regexp] or string pattern match (i.e. BuiltIn Library's196 [http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Should%20Match|Should197 Match])198 Examples:199 | Element Attribute Should Match | xpath = //*[contains(@text,'foo')] | text | *foobar |200 | Element Attribute Should Match | xpath = //*[contains(@text,'foo')] | text | f.*ar | regexp = True |201 | Element Attribute Should Match | xpath = //*[contains(@text,'foo')] | enabled | True |202 | 1. is a string pattern match i.e. the 'text' attribute should end with the string 'foobar'203 | 2. is a regular expression match i.e. the regexp 'f.*ar' should be within the 'text' attribute204 | 3. is a boolead match i.e. the 'enabled' attribute should be True205 _*NOTE: *_206 On Android the supported attribute names are hard-coded in the207 [https://github.com/appium/appium/blob/master/lib/devices/android/bootstrap/src/io/appium/android/bootstrap/AndroidElement.java|AndroidElement]208 Class's getBoolAttribute() and getStringAttribute() methods.209 Currently supported (appium v1.4.11):210 _contentDescription, text, className, resourceId, enabled, checkable, checked, clickable, focusable, focused, longClickable, scrollable, selected, displayed_211 _*NOTE: *_212 Some attributes can be evaluated in two different ways e.g. these evaluate the same thing:213 | Element Attribute Should Match | xpath = //*[contains(@text,'example text')] | name | txt_field_name |214 | Element Name Should Be | xpath = //*[contains(@text,'example text')] | txt_field_name | |215 """216 elements = self._element_find(locator, False, True)217 if len(elements) > 1:218 self._info("CAUTION: '%s' matched %s elements - using the first element only" % (locator, len(elements)))219 attr_value = elements[0].get_attribute(attr_name)220 # ignore regexp argument if matching boolean221 if isinstance(match_pattern, bool) or match_pattern.lower() == 'true' or match_pattern.lower() == 'false':222 if isinstance(match_pattern, bool):223 match_b = match_pattern224 else:225 match_b = ast.literal_eval(match_pattern.title())226 if isinstance(attr_value, bool):227 attr_b = attr_value228 else:229 attr_b = ast.literal_eval(attr_value.title())230 self._bi.should_be_equal(match_b, attr_b)231 elif regexp:232 self._bi.should_match_regexp(attr_value, match_pattern,233 msg="Element '%s' attribute '%s' should have been '%s' "234 "but it was '%s'." % (locator, attr_name, match_pattern, attr_value),235 values=False)236 else:237 self._bi.should_match(attr_value, match_pattern,238 msg="Element '%s' attribute '%s' should have been '%s' "239 "but it was '%s'." % (locator, attr_name, match_pattern, attr_value),240 values=False)241 # if expected != elements[0].get_attribute(attr_name):242 # raise AssertionError("Element '%s' attribute '%s' should have been '%s' "243 # "but it was '%s'." % (locator, attr_name, expected, element.get_attribute(attr_name)))244 self._info("Element '%s' attribute '%s' is '%s' " % (locator, attr_name, match_pattern))245 def element_should_contain_text(self, locator, expected, message=''):246 """Verifies element identified by ``locator`` contains text ``expected``.247 If you wish to assert an exact (not a substring) match on the text248 of the element, use `Element Text Should Be`.249 Key attributes for arbitrary elements are ``id`` and ``xpath``. ``message`` can be used to override the default error message.250 New in ATXLibrary 1.4.251 """252 self._info("Verifying element '%s' contains text '%s'."253 % (locator, expected))254 actual = self._get_text(locator)255 if not expected in actual:256 if not message:257 message = "Element '%s' should have contained text '%s' but " \258 "its text was '%s'." % (locator, expected, actual)259 raise AssertionError(message)260 def element_should_not_contain_text(self, locator, expected, message=''):261 """Verifies element identified by ``locator`` does not contain text ``expected``.262 ``message`` can be used to override the default error message.263 See `Element Should Contain Text` for more details.264 """265 self._info("Verifying element '%s' does not contain text '%s'."266 % (locator, expected))267 actual = self._get_text(locator)268 if expected in actual:269 if not message:270 message = "Element '%s' should not contain text '%s' but " \271 "it did." % (locator, expected)272 raise AssertionError(message)273 def element_text_should_be(self, locator, expected, message=''):274 """Verifies element identified by ``locator`` exactly contains text ``expected``.275 In contrast to `Element Should Contain Text`, this keyword does not try276 a substring match but an exact match on the element identified by ``locator``.277 ``message`` can be used to override the default error message.278 New in ATXLibrary 1.4.279 """280 self._info("Verifying element '%s' contains exactly text '%s'."281 % (locator, expected))282 element = self._element_find(locator, True, True)283 actual = element.text284 if expected != actual:285 if not message:286 message = "The text of element '%s' should have been '%s' but " \287 "in fact it was '%s'." % (locator, expected, actual)288 raise AssertionError(message)289 def get_webelement(self, locator):290 """Returns the first [http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement|WebElement] object matching ``locator``.291 Example:292 | ${element} | Get Webelement | id=my_element |293 | Click Element | ${element} | |294 New in ATXLibrary 1.4.295 """296 return self._element_find(locator, True, True)297 def get_webelements(self, locator):298 """Returns list of [http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement|WebElement] objects matching ``locator``.299 Example:300 | @{elements} | Get Webelements | id=my_element |301 | Click Element | @{elements}[2] | |302 This keyword was changed in ATXLibrary 1.4 in following ways:303 - Name is changed from `Get Elements` to current one.304 - Deprecated argument ``fail_on_error``, use `Run Keyword and Ignore Error` if necessary.305 New in ATXLibrary 1.4.306 """307 return self._element_find(locator, False, True)308 def get_element_attribute(self, locator, attribute):309 """Get element attribute using given attribute: name, value,...310 Examples:311 | Get Element Attribute | locator | name |312 | Get Element Attribute | locator | value |313 """314 elements = self._element_find(locator, False, True)315 ele_len = len(elements)316 if ele_len == 0:317 raise AssertionError("Element '%s' could not be found" % locator)318 elif ele_len > 1:319 self._info("CAUTION: '%s' matched %s elements - using the first element only" % (locator, len(elements)))320 try:321 attr_val = elements[0].get_attribute(attribute)322 self._info("Element '%s' attribute '%s' value '%s' " % (locator, attribute, attr_val))323 return attr_val324 except:325 raise AssertionError("Attribute '%s' is not valid for element '%s'" % (attribute, locator))326 # UiObject没有此类方法327 def get_element_location(self, locator):328 """Get element location329 Key attributes for arbitrary elements are `id` and `name`. See330 `introduction` for details about locating elements.331 """332 element = self._element_find(locator, True, True)333 element_location = element.pos_rel2abs()334 self._info("Element '%s' location: %s " % (locator, element_location))335 return element_location336 def get_element_size(self, locator):337 """Get element size338 Key attributes for arbitrary elements are `id` and `name`. See339 `introduction` for details about locating elements.340 """341 element = self._element_find(locator, True, True)342 element_size = element.size343 self._info("Element '%s' size: %s " % (locator, element_size))344 return element_size345 def get_text(self, locator):346 """Get element text (for hybrid and mobile browser use `xpath` locator, others might cause problem)347 Example:348 | ${text} | Get Text | //*[contains(@text,'foo')] |349 New in ATXLibrary 1.4.350 """351 text = self._get_text(locator)352 self._info("Element '%s' text is '%s' " % (locator, text))353 return text354 def get_matching_xpath_count(self, xpath):355 """Returns number of elements matching ``xpath``356 One should not use the `xpath=` prefix for 'xpath'. XPath is assumed.357 | *Correct:* |358 | ${count} | Get Matching Xpath Count | //android.view.View[@text='Test'] |359 | Incorrect: |360 | ${count} | Get Matching Xpath Count | xpath=//android.view.View[@text='Test'] |361 If you wish to assert the number of matching elements, use362 `Xpath Should Match X Times`.363 New in ATXLibrary 1.4.364 """365 count = len(self._element_find("xpath=" + xpath, False, False))366 return str(count)367 def text_should_be_visible(self, text, exact_match=False, loglevel='INFO'):368 """Verifies that element identified with text is visible.369 New in ATXLibrary 1.4.5370 """371 if not self._element_find_by_text(text, exact_match).is_displayed():372 self.log_source(loglevel)373 raise AssertionError("Text '%s' should be visible "374 "but did not" % text)375 def xpath_should_match_x_times(self, xpath, count, error=None, loglevel='INFO'):376 """Verifies that the page contains the given number of elements located by the given ``xpath``.377 One should not use the `xpath=` prefix for 'xpath'. XPath is assumed.378 | *Correct:* |379 | Xpath Should Match X Times | //android.view.View[@text='Test'] | 1 |380 | Incorrect: |381 | Xpath Should Match X Times | xpath=//android.view.View[@text='Test'] | 1 |382 ``error`` can be used to override the default error message.383 See `Log Source` for explanation about ``loglevel`` argument.384 New in ATXLibrary 1.4.385 """386 actual_xpath_count = len(self._element_find("xpath=" + xpath, False, False))387 if int(actual_xpath_count) != int(count):388 if not error:389 error = "Xpath %s should have matched %s times but matched %s times" \390 % (xpath, count, actual_xpath_count)391 self.log_source(loglevel)392 raise AssertionError(error)393 self._info("Current page contains %s elements matching '%s'."394 % (actual_xpath_count, xpath))395 # Private396 def _is_index(self, index_or_name):397 if index_or_name.startswith('index='):398 return True399 else:400 return False401 def _click_element_by_name(self, name):402 driver = self._current_application()403 try:404 element = driver.find_element_by_name(name)405 except Exception as e:406 raise e407 try:408 element.click()409 except Exception as e:410 raise 'Cannot click the element with name "%s"' % name411 def _find_elements_by_class_name(self, class_name):412 driver = self._current_application()413 elements = driver.find_elements_by_class_name(class_name)414 return elements415 def _find_element_by_class_name(self, class_name, index_or_name):416 elements = self._find_elements_by_class_name(class_name)417 if self._is_index(index_or_name):418 try:419 index = int(index_or_name.split('=')[-1])420 element = elements[index]421 except (IndexError, TypeError):422 raise 'Cannot find the element with index "%s"' % index_or_name423 else:424 found = False425 for element in elements:426 self._info("'%s'." % element.text)427 if element.text == index_or_name:428 found = True429 break430 if not found:431 raise 'Cannot find the element with name "%s"' % index_or_name432 return element433 def _get_class(self, platform_class_dict):434 return platform_class_dict.get(self._get_platform())435 def _is_support_platform(self, platform_class_dict):436 return platform_class_dict.has_key(self._get_platform())437 def _click_element_by_class_name(self, class_name, index_or_name):438 element = self._find_element_by_class_name(class_name, index_or_name)439 self._info("Clicking element '%s'." % element.text)440 try:441 element.click()442 except Exception as e:443 raise 'Cannot click the %s element "%s"' % (class_name, index_or_name)444 def _element_clear_text_by_locator(self, locator):445 try:446 element = self._element_find(locator, True, True)447 element.clear_text()448 except Exception as e:449 raise e450 def _element_input_text_by_locator(self, locator, text):451 try:452 element = self._element_find(locator, True, True)453 element.send_keys(text)454 except Exception as e:455 raise e456 def _element_input_text_by_class_name(self, class_name, index_or_name, text):457 try:458 element = self._find_element_by_class_name(class_name, index_or_name)459 except Exception as e:460 raise e461 self._info("input text in element as '%s'." % element.text)462 try:463 element.send_keys(text)464 except Exception as e:465 raise 'Cannot input text "%s" for the %s element "%s"' % (text, class_name, index_or_name)466 def _element_input_value_by_locator(self, locator, text):467 try:468 element = self._element_find(locator, True, True)469 element.set_text(text)470 except Exception as e:471 raise e472 def _element_find(self, locator, first_only, required, tag=None):473 application = self._current_application()474 elements = None475 if locator:476 _locator = locator477 elements = self._element_finder.find(application, _locator, tag)478 if required and elements is None:479 return None480 if first_only:481 if elements is None: return None482 return elements[0]483 elif isinstance(locator, UiObject):484 if first_only:485 return locator486 else:487 elements = [locator]488 # do some other stuff here like deal with list of webelements489 # ... or raise locator/element specific error if required490 return elements491 def _element_find_by_text(self, resourceId, text, exact_match=False):492 locator = {"resourceId": resourceId, "textvalue": text}493 element = self._element_find(locator, True, False)494 if element:495 return element496 else:497 raise Exception("find element: {} failed".format(locator))498 # else:499 # if exact_match:500 # _xpath = u'//*[@value="{}" or @label="{}"]'.format(text, text)501 # else:502 # _xpath = u'//*[contains(@label,"{}") or contains(@value, "{}")]'.format(text, text)503 # return self._element_find(_xpath, True, True)504 def _get_text(self, locator):505 element = self._element_find(locator, True, True)...

Full Screen

Full Screen

test_mobile.py

Source:test_mobile.py Github

copy

Full Screen

...171 webdriver.Remote = WebdriverRemoteMock172 mock_desk.get_current_context = MagicMock(return_value="Web")173 MobileLibrary.open_application(mock_desk, 'remote_url')174 MobileLibrary.scroll_up_to_text(mock_desk, "some_locator")175 mock_desk._element_find_by_text()._execute.assert_called()176 def test_scroll_up_to_text_native_app(self):177 mock_desk = MagicMock()178 webdriver.Remote = WebdriverRemoteMock179 mock_desk._current_application().execute_script = MagicMock()180 mock_desk.get_current_context = MagicMock(return_value="NATIVE")181 MobileLibrary.open_application(mock_desk, 'remote_url')182 MobileLibrary.scroll_up_to_text(mock_desk, "some_locator")183 mock_desk._current_application().execute_script.assert_called()184 def test_scroll_up_to_text_last_option(self):185 mock_desk = MagicMock()186 webdriver.Remote = WebdriverRemoteMock187 mock_desk._current_application().execute_script = MagicMock(side_effect=ValueError)188 MobileLibrary.open_application(mock_desk, 'remote_url')189 MobileLibrary.scroll_up_to_text(mock_desk, "some_locator")190 mock_desk._scroll_to_text.assert_called()191 def test_scroll_down(self):192 mock_desk = MagicMock()193 webdriver.Remote = WebdriverRemoteMock194 mock_desk.get_current_context = MagicMock(return_value="Web")195 MobileLibrary.open_application(mock_desk, 'remote_url')196 MobileLibrary.scroll_down(mock_desk, "some_locator")197 mock_desk._element_find()._execute.assert_called()198 def test_scroll_down_native_app(self):199 mock_desk = MagicMock()200 webdriver.Remote = WebdriverRemoteMock201 mock_desk._current_application().execute_script = MagicMock()202 mock_desk.get_current_context = MagicMock(return_value="NATIVE")203 MobileLibrary.open_application(mock_desk, 'remote_url')204 MobileLibrary.scroll_down(mock_desk, "some_locator")205 mock_desk._current_application().execute_script.assert_called()206 def test_scroll_down_to_text(self):207 mock_desk = MagicMock()208 webdriver.Remote = WebdriverRemoteMock209 mock_desk.get_current_context = MagicMock(return_value="Web")210 MobileLibrary.open_application(mock_desk, 'remote_url')211 MobileLibrary.scroll_down_to_text(mock_desk, "some_locator")212 mock_desk._element_find_by_text()._execute.assert_called()213 def test_scroll_down_to_text_native_app(self):214 mock_desk = MagicMock()215 webdriver.Remote = WebdriverRemoteMock216 mock_desk._current_application().execute_script = MagicMock()217 mock_desk.get_current_context = MagicMock(return_value="NATIVE")218 MobileLibrary.open_application(mock_desk, 'remote_url')219 MobileLibrary.scroll_down_to_text(mock_desk, "some_locator")220 mock_desk._current_application().execute_script.assert_called()221 def test_scroll_down_to_text_last_option(self):222 mock_desk = MagicMock()223 webdriver.Remote = WebdriverRemoteMock224 mock_desk._current_application().execute_script = MagicMock(side_effect=ValueError)225 mock_desk._is_text_present.side_effect = [False, True]226 MobileLibrary.open_application(mock_desk, 'remote_url')227 MobileLibrary.scroll_down_to_text(mock_desk, "some_locator")228 mock_desk._scroll_to_text.assert_called()229 def test_wait_for_and_tap(self):230 mock_desk = MagicMock()231 webdriver.Remote = WebdriverRemoteMock232 MobileLibrary.open_application(mock_desk, 'remote_url')233 MobileLibrary.wait_for_and_tap(mock_desk, "some_locator")234 mock_desk.tap.assert_called_with("some_locator", None, None, 1)235 def test_wait_for_and_tap_multiple(self):236 mock_desk = MagicMock()237 webdriver.Remote = WebdriverRemoteMock238 MobileLibrary.open_application(mock_desk, 'remote_url')239 MobileLibrary.wait_for_and_tap(mock_desk, "some_locator", count=4)240 mock_desk.tap.assert_called_with("some_locator", None, None, 4)241 def test_wait_for_and_tap_override_defaults(self):242 mock_desk = MagicMock()243 webdriver.Remote = WebdriverRemoteMock244 MobileLibrary.open_application(mock_desk, 'remote_url')245 MobileLibrary.wait_for_and_tap(mock_desk, "some_locator", x_offset=200, y_offset=100, count=4,246 error='some_error', timeout='10s')247 mock_desk.tap.assert_called_with("some_locator", 200, 100, 4)248 def test_capture_page_screenshot(self):249 mock_desk = MagicMock()250 mock_desk._get_screenshot_paths = MagicMock(return_value=['path', 'link'])251 MobileLibrary.capture_page_screenshot(mock_desk)252 mock_desk._get_screenshot_paths.assert_called()253 def test_capture_page_screenshot_else_case(self):254 mock_desk = MagicMock()255 mock_desk._get_screenshot_paths = MagicMock(return_value=['path', 'link'])256 del mock_desk._current_application().get_screenshot_as_file257 MobileLibrary.capture_page_screenshot(mock_desk, 'filename')258 mock_desk._get_screenshot_paths.assert_called()259 def test_save_appium_screenshot(self):260 mock_desk = MagicMock()261 MobileLibrary.save_appium_screenshot(mock_desk)262 mock_desk.capture_page_screenshot.assert_called()263 def test_wait_until_page_contains_private(self):264 mock_desk = MagicMock()265 MobileLibrary._wait_until_page_contains(mock_desk, 'some_text', 5)266 mock_desk._wait_until.asser_called_with('some_text', 5)267 def test_wait_until_page_contains_element_private(self):268 mock_desk = MagicMock()269 MobileLibrary._wait_until_page_contains_element(mock_desk, 'some_element', 5)270 mock_desk._wait_until.assert_called_with(5, "Element 'some_element' did not appear in "271 "<TIMEOUT>", unittest.mock.ANY, 'some_element')272 def test_platform_dependant_press_private(self):273 mock_desk = MagicMock()274 mock_desk._is_ios = MagicMock(return_value=False)275 MobileLibrary._platform_dependant_press(mock_desk, MagicMock(), 'some_element')276 def test_platform_dependant_press_ios_private(self):277 mock_desk = MagicMock()278 mock_desk._is_ios = MagicMock(return_value=True)279 MobileLibrary._platform_dependant_press(mock_desk, MagicMock(), 'some_element')280 def test_platform_dependant_press_delay_set_private(self):281 mock_desk = MagicMock()282 mock_desk._is_ios = MagicMock(return_value=True)283 MobileLibrary._platform_dependant_press(mock_desk, MagicMock(), 'some_element', delay=500)284 def test_element_find_by_text_ios(self):285 mock_desk = MagicMock()286 mock_desk._is_ios = MagicMock(return_value=True)287 webdriver.Remote = WebdriverRemoteMock288 mock_desk._element_find = MagicMock()289 MobileLibrary._element_find_by_text(mock_desk, "some_text")290 mock_desk._element_find.assert_called_with('some_text', True, False)291 def test_element_find_by_text_ios_exact(self):292 mock_desk = MagicMock()293 mock_desk._is_ios = MagicMock(return_value=True)294 webdriver.Remote = WebdriverRemoteMock295 mock_desk._element_find = MagicMock(return_value=False)296 MobileLibrary._element_find_by_text(mock_desk, "some_text", True)297 mock_desk._element_find.assert_called_with('//*[@value="some_text" or @label="some_text"]', True, True)298 def test_element_find_by_text_ios_not_exact(self):299 mock_desk = MagicMock()300 mock_desk._is_ios = MagicMock(return_value=True)301 webdriver.Remote = WebdriverRemoteMock302 mock_desk._element_find = MagicMock(return_value=False)303 MobileLibrary._element_find_by_text(mock_desk, "some_text", False)304 mock_desk._element_find.assert_called_with('//*[contains(@label,"some_text") or contains(@value, "some_text") '305 'or contains(text(), "some_text")]', True, True)306 def test_element_find_by_text_android_exact(self):307 mock_desk = MagicMock()308 mock_desk._is_ios = MagicMock(return_value=False)309 mock_desk._is_android = MagicMock(return_value=True)310 webdriver.Remote = WebdriverRemoteMock311 mock_desk._element_find = MagicMock(return_value=False)312 MobileLibrary._element_find_by_text(mock_desk, "some_text", True)313 mock_desk._element_find.assert_called_with('//*[@text="some_text"]', True, True)314 def test_element_find_by_text_android_not_exact(self):315 mock_desk = MagicMock()316 mock_desk._is_ios = MagicMock(return_value=False)317 mock_desk._is_android = MagicMock(return_value=True)318 webdriver.Remote = WebdriverRemoteMock319 mock_desk._element_find = MagicMock(return_value=False)320 MobileLibrary._element_find_by_text(mock_desk, "some_text", False)321 mock_desk._element_find.assert_called_with('//*[contains(@text,"some_text")]', True, True)322 def test_is_text_visible(self):323 mock_desk = MagicMock()324 webdriver.Remote = WebdriverRemoteMock325 mock_desk._element_find_by_text().is_displayed = MagicMock(return_value=True)326 result = MobileLibrary._is_text_visible(mock_desk, "some_text")327 self.assertTrue(result)328 def test_is_text_visible_not_found(self):329 mock_desk = MagicMock()330 webdriver.Remote = WebdriverRemoteMock331 mock_desk._element_find_by_text = MagicMock(return_value=None)332 result = MobileLibrary._is_text_visible(mock_desk, "some_text")333 self.assertIsNone(result)334 def test_scroll_to_text_ios_visible_no_scroll(self):335 mock_desk = MagicMock()336 webdriver.Remote = WebdriverRemoteMock337 mock_desk._is_android = MagicMock(return_value=False)338 mock_desk._is_ios = MagicMock(return_value=True)339 mock_desk._is_text_visible = MagicMock(return_value=True)...

Full Screen

Full Screen

MobileLibrary.py

Source:MobileLibrary.py Github

copy

Full Screen

...191 to find the element. The ``swipe_count`` limits the number of these swipes before the keyword gives up,192 defaults to 10."""193 try:194 driver = self._current_application()195 element = self._element_find_by_text(text, exact_match)196 if not self.get_current_context().startswith("NATIVE"):197 element._execute("getElementLocationOnceScrolledIntoView")198 else:199 driver.execute_script("mobile: scroll", {"direction": 'down', 'elementid': element})200 except ValueError:201 self._scroll_to_text(text, 'down', swipe_count)202 @keyword("Scroll Up To Text")203 def scroll_up_to_text(self, text, exact_match=False, swipe_count=10):204 """Scrolls down to ``text``.205 In some instances the default scroll behavior does not work. In this case the keyword will use small swipes206 to find the element. The ``swipe_count`` limits the number of these swipes before the keyword gives up,207 defaults to 10."""208 try:209 driver = self._current_application()210 element = self._element_find_by_text(text, exact_match)211 if not self.get_current_context().startswith("NATIVE"):212 element._execute("getElementLocationOnceScrolledIntoView")213 else:214 driver.execute_script("mobile: scroll", {"direction": 'up', 'elementid': element})215 except ValueError:216 self._scroll_to_text(text, 'up', swipe_count)217 def scroll_down(self, locator):218 """Scrolls down to an element identified by ``locator``."""219 driver = self._current_application()220 element = self._element_find(locator, True, True)221 if not self.get_current_context().startswith("NATIVE"):222 element._execute("getElementLocationOnceScrolledIntoView")223 else:224 driver.execute_script("mobile: scroll", {"toVisible": 'down', 'elementid': element})225 def scroll_up(self, locator):226 """Scrolls up to an element identified by ``locator``."""227 driver = self._current_application()228 element = self._element_find(locator, True, True)229 if not self.get_current_context().startswith("NATIVE"):230 element._execute("getElementLocationOnceScrolledIntoView")231 else:232 driver.execute_script("mobile: scroll", {"direction": 'up', 'elementid': element})233 @keyword("Wait For And Tap")234 def wait_for_and_tap(self, locator, x_offset=None, y_offset=None, count=1, timeout=None,235 error=None):236 """ Wait for and then Tap element identified by ``locator``.237 Args:238 - ``x_offset`` - (optional) x coordinate to tap, relative to the top left corner of the element.239 - ``y_offset`` - (optional) y coordinate. If y is used, x must also be set, and vice versa240 - ``count`` - can be used to tap multiple times241 - ``timeout`` - time in seconds to locate the element, defaults to global timeout242 - ``error`` - (optional) used to override the default error message.243 """244 self._wait_until_page_contains_element(locator, timeout, error)245 self.tap(locator, x_offset, y_offset, count)246 def capture_page_screenshot(self, filename=None):247 """Takes a screenshot of the current page and embeds it into the log.248 `filename` argument specifies the name of the file to write the249 screenshot into. If no `filename` is given, the screenshot is saved into file250 `appium-screenshot-<counter>.png` under the directory where251 the Robot Framework log file is written into. The `filename` is252 also considered relative to the same directory, if it is not253 given in absolute format.254 `css` can be used to modify how the screenshot is taken. By default255 the bakground color is changed to avoid possible problems with256 background leaking when the page layout is somehow broken.257 See `Save Appium Screenshot` for a screenshot that will be unique across reports258 """259 return AppiumCommon.capture_page_screenshot(self, filename)260 @keyword("Save Appium Screenshot")261 def save_appium_screenshot(self):262 """Takes a screenshot with a unique filename to be stored in Robot Framework compiled263 reports."""264 return AppiumCommon.save_appium_screenshot(self)265 266 # Private267 def _wait_until_page_contains(self, text, timeout=None, error=None):268 """Internal version to avoid duplicate screenshots"""269 AppiumCommon.wait_until_page_contains(self, text, timeout, error)270 def _wait_until_page_contains_element(self, locator, timeout=None, error=None):271 """Internal version to avoid duplicate screenshots"""272 if not error:273 error = "Element '%s' did not appear in <TIMEOUT>" % locator274 self._wait_until(timeout, error, self._is_element_present, locator)275 def _platform_dependant_press(self, actions, element, delay=1500):276 """Decide press action based on platform"""277 AppiumCommon._platform_dependant_press(self, actions, element, delay)278 def _element_find_by_text(self, text, exact_match=False):279 if self._is_ios():280 element = self._element_find(text, True, False)281 if element:282 return element283 if exact_match:284 _xpath = u'//*[@value="{}" or @label="{}"]'.format(text, text)285 else:286 _xpath = u'//*[contains(@label,"{}") or contains(@value, "{}") or contains(text(), "{}")]'.format(text, text, text)287 elif self._is_android():288 if exact_match:289 _xpath = u'//*[@{}="{}"]'.format('text', text)290 else:291 _xpath = u'//*[contains(@text,"{}")]'.format(text)292 return self._element_find(_xpath, True, True)293 def _is_text_visible(self, text, exact_match=False):294 element = self._element_find_by_text(text, exact_match)295 if element is not None:296 return element.is_displayed()297 return None298 def _scroll_to_text(self, text, swipe_direction, swipe_count=10):299 """This is a more manual attempt in case the first scroll does not work."""300 for _ in range(swipe_count):301 if self._is_android() and self._is_text_present(text):302 return True303 if self._is_ios() and self._is_text_visible(text):304 return True305 if swipe_direction.lower() == 'up':306 self.swipe_by_percent(50, 25, 50, 75) # use swipe by direction if its ever implemented307 elif swipe_direction.lower() == 'down':308 self.swipe_by_percent(50, 75, 50, 25) # use swipe by direction if its ever implemented...

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 robotframework-appiumlibrary 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