How to use element_location method in AutoItDriverServer

Best Python code snippet using AutoItDriverServer_python

native_app_wrapper.py

Source:native_app_wrapper.py Github

copy

Full Screen

1import time2from factory.handling.assertion import Assertion as Assert3from factory.handling.running_exception import RunningException as Rexc4from factory.singleton_web_driver import WebDriver5from appium.webdriver.common.mobileby import MobileBy as MBy6from appium.webdriver.common.touch_action import TouchAction7from selenium.webdriver.support.ui import Select8from factory.utils.StringsUtil import StringUtil as String9from factory.utils.DataEncryptedUtil import DataEncrypted as RandomData10ELEMENT_LOCATION = "/html/body"11driver = WebDriver.use()12class BaseAppPage(WebDriver):13 @staticmethod14 def assert_that(comparative_value=""):15 return Assert(comparative_value)16 def scroll_into_view(self, by_type, element_location):17 self.wait_for_element(by_type, element_location)18 WebDriver.use().execute_script("mobile: scroll", {"direction": "down"})19 return self20 def drag_to_view(self, by_type, element_location):21 self.wait_for_element(by_type, element_location)22 element_to_tap = BaseAppPage.use().find_element_by_xpath(element_location)23 element_to_drag_to = BaseAppPage.use().find_element_by_xpath()24 WebDriver.use().driver.scroll(element_to_tap, element_to_drag_to)25 return self26 @staticmethod27 def hide_keyboard():28 WebDriver.use().hide_keyboard()29 def accept_alert(self):30 try:31 time.sleep(1)32 WebDriver.use().switch_to_alert().accept()33 except:34 WebDriver.use().execute_script("mobile: acceptAlert")35 return self36 def cancel_alert(self):37 try:38 time.sleep(1)39 WebDriver.use().switch_to_alert().dismiss()40 except:41 WebDriver.use().execute_script("mobile: dismissAlert")42 return self43 def is_the_element_presented(self, by_type, element_location, timeout=30):44 self.get_page_to_load()45 return self.wait_for_element(46 by_type, element_location, is_presented=True, handle_timeout=timeout47 )48 def accept_notification(self, by_type, element_location):49 try:50 self.wait_for_element(by_type, element_location, handle_timeout=3)51 except:52 pass53 finally:54 if self.is_the_element_presented(by_type, element_location, timeout=2) is False:55 pass56 else:57 self.click_on(by_type, element_location, timeout=2)58 try:59 self.accept_alert()60 except:61 self.click_on(by_type, element_location, timeout=2)62 return self63 @staticmethod64 def get_element_text(by_type, element_location, is_visible=False):65 element_location = str(element_location)66 try:67 BaseAppPage.wait_for_element(by_type, element_location, is_visible=is_visible)68 element = BaseAppPage.get_element_by(by_type, element_location)69 try:70 BaseAppPage.wait_for_element(by_type, element_location, is_presented=True)71 text = WebDriver.execute_javascript("return arguments[0].textContent", element)72 return text73 except:74 text = str(element.text).strip()75 return text76 except ValueError as ve:77 Rexc.raise_assertion_error(78 f"The element '{element_location}' does not match the text value expected! ", ve79 )80 @staticmethod81 def type_text(82 input_text,83 by_type,84 element_location,85 is_clickable=False,86 clear_field=False,87 hide_keyboard=True,88 ):89 if BaseAppPage.is_not_empty_value(input_text):90 try:91 if String.is_not_blank_or_null(input_text):92 BaseAppPage.wait_for_element(93 by=by_type,94 location=element_location,95 is_visible=True,96 is_clickable=is_clickable,97 )98 element = BaseAppPage.get_element_by(by_type, element_location)99 input_text_formatted = BaseAppPage.generate_random_string_data(input_text)100 if clear_field:101 element.clear()102 element.send_keys(str(input_text_formatted))103 if hide_keyboard:104 BaseAppPage.hide_keyboard()105 except ValueError as ve:106 Rexc.raise_assertion_error(107 f"The element '{element_location}' is not iterable or value {input_text} not matches! ",108 ve,109 )110 @staticmethod111 def click_on(112 by_type="",113 element_location="",114 is_visible=False,115 by_id=False,116 by_xpath=False,117 by_css_selector=False,118 by_name=False,119 by_tagname=False,120 by_classname=False,121 by_custom=False,122 by_accessibility_id=False,123 by_ios_uiautomation=False,124 by_android_uiautomator=False,125 by_android_viewtag=False,126 by_ios_class_chain=False,127 by_ios_predicate=False,128 by_image=False,129 timeout=30,130 ):131 BaseAppPage.wait_for_element(132 by_type,133 element_location,134 is_visible=is_visible,135 is_clickable=True,136 handle_timeout=timeout,137 )138 if by_type != "":139 element = BaseAppPage.get_element_by(by_type, element_location)140 if element.is_displayed():141 try:142 BaseAppPage.get_element_by(by_type, element_location).click()143 except:144 BaseAppPage.get_element_by(by_type, element_location).click()145 finally:146 BaseAppPage.log_action(element_location, action_name="Click")147 else:148 BaseAppPage.click_on_element_by_id(element_location)149 fetch_and_click = (150 lambda click_method, by_type_state: click_method if by_type_state is True else False151 )152 fetch_and_click(BaseAppPage.click_on_element_by_id(element_location), by_id)153 fetch_and_click(BaseAppPage.click_on_element_by_xpath(element_location), by_xpath)154 fetch_and_click(155 BaseAppPage.click_on_element_by_css_selector(element_location), by_css_selector156 )157 fetch_and_click(BaseAppPage.click_on_element_by_name(element_location), by_name)158 fetch_and_click(BaseAppPage.click_on_element_by_tag_name(element_location), by_tagname)159 fetch_and_click(160 BaseAppPage.click_on_element_by_class_name(element_location), by_classname161 )162 fetch_and_click(BaseAppPage.click_on_element_by_custom(element_location), by_custom)163 fetch_and_click(164 BaseAppPage.click_on_element_by_accessibility_id(element_location),165 by_accessibility_id,166 )167 fetch_and_click(168 BaseAppPage.click_on_element_by_ios_uiautomation(element_location),169 by_ios_uiautomation,170 )171 fetch_and_click(172 BaseAppPage.click_on_element_by_android_uiautomator(element_location),173 by_android_uiautomator,174 )175 fetch_and_click(176 BaseAppPage.click_on_element_by_android_viewtag(element_location),177 by_android_viewtag,178 )179 fetch_and_click(180 BaseAppPage.click_on_element_by_ios_class_chain(element_location),181 by_ios_class_chain,182 )183 fetch_and_click(184 BaseAppPage.click_on_element_by_ios_predicate(element_location), by_ios_predicate185 )186 fetch_and_click(BaseAppPage.click_on_element_by_image(element_location), by_image)187 @staticmethod188 def click_on_element_by_accessibility_id(element_location):189 BaseAppPage.wait_for_element(MBy.ACCESSIBILITY_ID, element_location, is_clickable=True)190 BaseAppPage.find_by_accessibility_id(element_location).click()191 @staticmethod192 def click_on_element_by_android_uiautomator(element_location):193 BaseAppPage.wait_for_element(MBy.ANDROID_UIAUTOMATOR, element_location, is_clickable=True)194 BaseAppPage.find_by_android_uiautomator(element_location).click()195 @staticmethod196 def click_on_element_by_android_viewtag(element_location):197 BaseAppPage.wait_for_element(MBy.ANDROID_VIEWTAG, element_location, is_clickable=True)198 BaseAppPage.find_by_android_viewtag(element_location).click()199 @staticmethod200 def click_on_element_by_xpath(element_location):201 BaseAppPage.wait_for_element(MBy.XPATH, element_location)202 BaseAppPage.find_by_xpath(element_location).click()203 @staticmethod204 def click_on_element_by_css_selector(element_location):205 BaseAppPage.wait_for_element(MBy.CSS_SELECTOR, element_location)206 BaseAppPage.find_by_css_selector(element_location).click()207 @staticmethod208 def click_on_element_by_class_name(element_location):209 BaseAppPage.wait_for_element(MBy.CLASS_NAME, element_location)210 BaseAppPage.find_by_class_name(element_location).click()211 @staticmethod212 def click_on_element_by_custom(element_location):213 BaseAppPage.wait_for_element(MBy.CUSTOM, element_location)214 BaseAppPage.find_by_custom(element_location).click()215 @staticmethod216 def click_on_element_by_id(element_location):217 BaseAppPage.wait_for_element(MBy.ID, element_location)218 BaseAppPage.find_by_id(element_location).click()219 @staticmethod220 def click_on_element_by_image(element_location):221 BaseAppPage.wait_for_element(MBy.IMAGE, element_location)222 BaseAppPage.find_by_image(element_location).click()223 @staticmethod224 def click_on_element_by_ios_class_chain(element_location):225 BaseAppPage.wait_for_element(MBy.IOS_CLASS_CHAIN, element_location)226 BaseAppPage.find_by_ios_class_chain(element_location).click()227 @staticmethod228 def click_on_element_by_ios_predicate(element_location):229 BaseAppPage.wait_for_element(MBy.IOS_PREDICATE, element_location)230 BaseAppPage.find_by_ios_predicate(element_location).click()231 @staticmethod232 def click_on_element_by_ios_uiautomation(element_location):233 BaseAppPage.wait_for_element(MBy.IOS_UIAUTOMATION, element_location)234 BaseAppPage.find_by_ios_uiautomation(element_location).click()235 @staticmethod236 def click_on_element_by_name(element_location):237 BaseAppPage.wait_for_element(MBy.NAME, element_location)238 BaseAppPage.find_by_name(element_location).click()239 @staticmethod240 def click_on_element_by_tag_name(element_location):241 BaseAppPage.wait_for_element(MBy.TAG_NAME, element_location)242 BaseAppPage.find_by_tag_name(element_location).click()243 @staticmethod244 def click_on_list_of_elements(by_type, root_elements_location):245 element_list_ = BaseAppPage.get_elements_by(by_type, root_elements_location)246 for item in range(len(element_list_)):247 element_list_[item].click()248 @staticmethod249 def format_prices_to_number(by_type, element_location):250 items_found = BaseAppPage.get_elements_by(by_type, element_location)251 labels_found = []252 for item in items_found:253 price_fmt = String.convert_currency_to_number(value_to_format=item.text)254 labels_found.append(price_fmt)255 return labels_found256 @staticmethod257 def format_numbers_to_price(labels, by_type="", element_location="", symbol=""):258 items_found = (259 BaseAppPage.get_elements_by(by_type, element_location)260 if element_location != ""261 else labels262 )263 BaseAppPage.wait_for_element(by=by_type, location=element_location)264 for item in items_found:265 price = String.extract_number(item.text)266 price_fmt = String.convert_number_to_currency(value_to_format=price, currency=symbol)267 labels.append(price_fmt)268 return labels269 @staticmethod270 def tap(by_type="", element_location=""):271 element = BaseAppPage.find_by(by_type, element_location)272 action = TouchAction(WebDriver.use())273 action.tap(element).perform()274 @staticmethod275 def choose_random_value(values_list):276 list_size = len(values_list) - 1277 random_option = int(278 RandomData.generate_random_data(279 length=3, start_threshold=0, end_threshold=list_size, step=1, only_numbers=True280 )281 )282 return values_list[random_option]283 @staticmethod284 def _choose_random_element(by_type, element_location):285 BaseAppPage.wait_for_element(by_type, element_location)286 options_ = BaseAppPage.list_element_strings(by_type, element_location)287 total_options = len(options_) - 1288 single_item_max = 1289 threshold = 0 if total_options < single_item_max else single_item_max290 random_value = (291 threshold292 if total_options <= single_item_max293 else RandomData.generate_random_data(294 length=4, start_threshold=1, end_threshold=total_options, only_numbers=True295 )296 )297 random_option = options_[int(random_value)]298 print(f" └> Random option chosen: {random_option}")299 return random_option300 @staticmethod301 def find_a_limit_value_in_list(by_type, element_location, max_value=False):302 """Find Max or Min value in list of elements303 Args:304 by_type (By): Use MBy that defines the drop_locator305 element_location (str): Locator string from an element (can be an XPATH, ID, CSS_SELECTOR, etc.)306 max_value (bool, optional): Set it to True if you need only a max value into a list found. Defaults to False.307 Returns:308 [int]: Value found according parameter expected: if max or min number into the list309 """310 BaseAppPage.wait_for_element(by_type, element_location)311 items_found = BaseAppPage.find_elements_by(by_type, element_location)312 labels_found = [float(String.extract_decimal(item.text)[0]) for item in items_found]313 return max(labels_found) if max_value else min(labels_found)314 @staticmethod315 def list_element_strings(by_type, element_location, options_location=""):316 options_locator = (by_type, element_location + options_location)317 BaseAppPage.wait_for_element(*options_locator)318 items_found = BaseAppPage.find_elements_by(*options_locator)319 labels_found = [item.text for item in items_found]320 if BaseAppPage.wait_for_element(*options_locator, is_presented=True):321 pass322 return labels_found[0].split("\n") if len(labels_found) == 1 else labels_found323 @staticmethod324 def select_dropdown_item(325 str_option,326 str_autocomplete="",327 root_by_type=MBy.XPATH,328 root_selector="",329 xpath_for_root_option="",330 xpath_with_a_option_set="",331 is_combobox=False,332 is_visible=False,333 ):334 """335 Select a dropdown item or find an option in an autocomplete input text filter.336 Args:337 str_option (str): The value used to be selected in the component338 str_autocomplete (str, optional): Text to be used in a search field with autocomplete function. Defaults to "".339 root_by_type (By.[TYPE], optional): A type for the "root_selector" argument. It can be a ID, XPATH or CSS_SELECTOR. Defaults to By.XPATH.340 root_selector (str, optional): A XPATH or CSS_SELECTOR to locate the root of a dropdown component. Defaults to "".341 xpath_for_root_option (str, optional): Generic selector to locate the root of elements presented in a visible dropdown list. Defaults to "".342 xpath_with_a_option_set (str, optional): Selector to a specific item presented in a visible dropdown list. Defaults to "".343 is_combobox (bool, optional): If you are considering the dropdown selection as a simple combobox. Defaults to False.344 is_visible (bool, optional): If you really needs the element visible at the page.345 """346 if is_combobox:347 BaseAppPage._combobox(str_option, root_by_type, root_selector)348 else:349 BaseAppPage._dynamic_dropdown(350 str_option,351 str_autocomplete,352 root_by_type,353 root_selector,354 xpath_for_root_option,355 xpath_with_a_option_set,356 is_component_visible=is_visible,357 )358 @staticmethod359 def _dynamic_dropdown(360 str_option,361 str_autocomplete,362 root_by_type,363 root_selector,364 xpath_for_root_option,365 xpath_with_a_option_set,366 is_component_visible,367 ):368 if BaseAppPage.is_not_empty_value(str_option):369 if str_autocomplete != "":370 BaseAppPage.type_text(371 str_autocomplete,372 root_by_type,373 root_selector,374 is_clickable=True,375 )376 else:377 BaseAppPage.click_on(root_by_type, root_selector, is_visible=is_component_visible)378 dropdown_item_value = (379 BaseAppPage._choose_random_element(MBy.XPATH, xpath_for_root_option)380 if str_option == "" and xpath_with_a_option_set == ""381 else str_option382 )383 text_finder = BaseAppPage.chain_dynamic_xpath_functions(384 searchable_text=dropdown_item_value385 )386 has_all_symbol = (387 "//*"388 if BaseAppPage.wait_for_element(389 MBy.XPATH,390 f"{xpath_for_root_option}//*{text_finder}",391 is_presented=True,392 )393 is True394 else ""395 )396 full_selector_item = (397 f"{xpath_for_root_option}{has_all_symbol}{text_finder}"398 if xpath_for_root_option != ""399 else xpath_with_a_option_set400 )401 print(f" └> Dynamic option to selection:\n {full_selector_item}")402 BaseAppPage.wait_for_element(MBy.XPATH, full_selector_item)403 BaseAppPage.click_on(MBy.XPATH, full_selector_item, is_visible=is_component_visible)404 @staticmethod405 def _combobox(option, by_type, element_location):406 if BaseAppPage.is_not_empty_value(option):407 BaseAppPage.wait_for_element(by_type, element_location, is_clickable=True)408 select = Select(BaseAppPage.get_element_by(by_type, element_location))409 try:410 select.select_by_value(option)411 except:412 if String.is_not_blank_or_null(option):413 select.select_by_visible_text(option)...

Full Screen

Full Screen

PageFunction.py

Source:PageFunction.py Github

copy

Full Screen

1#!\usr\bin\env python2# -*- coding:utf-8 -*-3'''4Title: 页面元素工厂5Description: 继承Base,对页面元素进行二次封装,6读取json格式元素地址,使其能够直接使用element文件中的元素名7直接调用该元素所对应的操作。8@author: Xushenwei9@update: 2018年9月18日10@editor:11'''12import json13from selenium.webdriver.common.by import By14from page_obj.models.Base import Page15class FunctionFactory(Page):16 '''元素方法工厂'''17 def __init__(self, seleniumdriver, jsonfilename):18 self.driver = seleniumdriver19 self.jsonfilename = jsonfilename20 self.timeout = 1021 self.basedir = self.Base_dir()22 def make_function_click_by_css(self, element_location):23 """使用css定位来点击元素"""24 def function_click_by_css():25 self.find_element(By.CSS_SELECTOR, element_location).click()26 return function_click_by_css27 def make_function_sendkeys_by_css(self, element_location):28 """使用css定位来输入信息"""29 def function_sendkeys_by_css(value, clear_first=True, click_first=True, id_name=False):30 try:31 if id_name:32 js = "document.getElementById('" + id_name + "').removeAttribute('readonly');"33 self.script(js)34 if click_first:35 self.find_element(By.CSS_SELECTOR, element_location).click()36 if clear_first:37 self.find_element(By.CSS_SELECTOR, element_location).clear()38 self.find_element(By.CSS_SELECTOR, element_location).send_keys(value)39 except AttributeError:40 print("Can't find element as %s" % element_location)41 return function_sendkeys_by_css42 def make_function_hint_by_css(self, element_location):43 """使用css定位来获取验证元素文本"""44 def function_hint_by_css():45 return self.find_element(By.CSS_SELECTOR, element_location)46 return function_hint_by_css().text47 def ReadJsonData(self):48 """从Json文件中读取元素内容"""49 jsonpath = self.basedir + '/test_case/page_obj/' + self.jsonfilename +'.json'50 file = open(jsonpath, 'rb')51 fileJsondata = json.loads(file.read())52 file.close()53 return fileJsondata54 def Click(self, element_name):55 """使用元素名称来操控元素点击动作"""56 element_location = self.ReadJsonData()[element_name]57 function = self.make_function_click_by_css(element_location)58 function()59 def SendKeys(self, element_name, value):60 """使用元素名称来操控输入动作"""61 element_location = self.ReadJsonData()[element_name]62 function = self.make_function_sendkeys_by_css(element_location)63 function(value)64 def Hint(self, element_name):65 """使用元素名称来操控元素点击动作"""66 element_location = self.ReadJsonData()[element_name]67 function = self.make_function_hint_by_css(element_location)68 return function69if __name__ == "__main__":...

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