1. 程式人生 > 其它 >基於Appium,封裝自己的常用方法

基於Appium,封裝自己的常用方法

Appium算是老牌移動端App自動化測試工具了,在使用它的過程中,使用者經常會根據個人習慣,把較常用的方法封裝在一起,方便呼叫。以下是我的封裝,希望對你有啟發。

from typing import Dict, NoReturn, Tuple, List, Union, Optional
from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from appium.webdriver.webelement import
WebElement as MobileWebElement from selenium.webdriver.common.by import By from loguru import logger import time class AppDriver: def __init__(self, command_executor: str, desired_caps: Optional[Dict]) -> NoReturn: self.driver = webdriver.Remote(command_executor, desired_caps)
def find_element(self, element: Tuple[str, Union[str, Dict]]) -> MobileWebElement: """ 尋找元素 """ by = element[0] value = element[1] try: if self.is_element_exist(element): if by == "id": return self.driver.find_element(By.ID, value)
elif by == "name": return self.driver.find_element(By.NAME, value) elif by == "class": return self.driver.find_element(By.CLASS_NAME, value) elif by == "text": return self.driver.find_element(By.LINK_TEXT, value) elif by == "partial_text": return self.driver.find_element(By.PARTIAL_LINK_TEXT, value) elif by == "xpath": return self.driver.find_element(By.XPATH, value) elif by == "css": return self.driver.find_element(By.CSS_SELECTOR, value) elif by == "tag": return self.driver.find_element(By.TAG_NAME, value) else: raise NameError("Please enter the correct targeting elements,'id','name','class','text','xpath','css'.") except Exception as e: logger.error(">>>>>>>> failed to find element: %s is %s. Error: %s" % (by, value, e)) def find_elements(self, element: Tuple[str, Union[str, Dict]]) -> Union[List[MobileWebElement], List]: """ 尋找一組元素 """ by = element[0] value = element[1] try: if self.is_element_exist(element): if by == "id": return self.driver.find_elements(By.ID, value) elif by == "name": return self.driver.find_elements(By.NAME, value) elif by == "class": return self.driver.find_elements(By.CLASS_NAME, value) elif by == "text": return self.driver.find_elements(By.LINK_TEXT, value) elif by == "partial_text": return self.driver.find_elements(By.PARTIAL_LINK_TEXT, value) elif by == "xpath": return self.driver.find_elements(By.XPATH, value) elif by == "css": return self.driver.find_elements(By.CSS_SELECTOR, value) elif by == "tag": return self.driver.find_elements(By.TAG_NAME, value) else: raise NameError("Please enter the correct targeting elements,'id','name','class','text','xpath','css'.") except Exception as e: logger.error(">>>>>>>> failed to find elements: %s is %s. Error: %s" % (by, value, e)) def find_all_child_element_by_xpath(self, element: Tuple[str, Union[str, Dict]]) -> Union[List[MobileWebElement], List]: """ 尋找元素的所有子元素 """ by = element[0] value = element[1] try: if self.is_element_exist(element): if by == "xpath": child_value = value + '/child::*' return self.driver.find_elements(By.XPATH, child_value) else: raise NameError("Please enter the correct targeting elements 'xpath'.") except Exception as e: logger.error(">>>>>>>> failed to find elements: %s is %s. Error: %s" % (by, value, e)) def save_screenshot(self, picture_name: str) -> NoReturn: """ 獲取螢幕截圖 """ fmt = '%Y%m%d%H%M%S' # 定義時間顯示格式 date = time.strftime(fmt, time.localtime(time.time())) # 把傳入的元組按照格式,輸出字串 picture_name = "../Result/" + picture_name + "-" + date + ".jpg" self.driver.get_screenshot_as_file(picture_name) def get_screen_size(self) -> Tuple[int, int]: """ 獲取手機螢幕大小 """ x = self.driver.get_window_size()['width'] y = self.driver.get_window_size()['height'] return x, y def swipe_screen(self, direction: str, duration_ms: int = 800) -> NoReturn: """ 螢幕向上滑動 """ location = self.get_screen_size() if direction.lower() == "up": x = int(location[0] * 0.5) start_y = int(location[1] * 0.75) end_y = int(location[1] * 0.25) self.driver.swipe(x, start_y, x, end_y, duration_ms) elif direction.lower() == "down": x = int(location[0] * 0.5) start_y = int(location[1] * 0.25) end_y = int(location[1] * 0.75) self.driver.swipe(x, start_y, x, end_y, duration_ms) elif direction.lower() == "left": start_x = int(location[0] * 0.75) y = int(location[1] * 0.5) end_x = int(location[0] * 0.05) self.driver.swipe(start_x, y, end_x, y, duration_ms) elif direction.lower() == "right": start_x = int(location[0] * 0.05) y = int(location[1] * 0.5) end_x = int(location[0] * 0.75) self.driver.swipe(start_x, y, end_x, y, duration_ms) else: print("請輸入正確的方向") def tap_screen(self, positions: List[Tuple[int, int]], duration: Optional[int] = None) -> NoReturn: """ 用最多五個手指輕拍一個特定的地方,保持一定的時間 用法:tap_screen([(100, 20), (100, 60), (100, 100)], 500) """ self.driver.tap(positions, duration) def click(self, element: Tuple[str, Union[str, Dict]], found_index: int = -1) -> NoReturn: """ 點選按鈕 """ if found_index == -1: self.find_element(element).click() else: self.find_elements(element)[found_index].click() def send_keys(self, element: Tuple[str, Union[str, Dict]], value: str, clear_first: bool = False, click_first: bool = False, found_index: int = -1) -> NoReturn: """ 鍵盤輸入 """ if found_index == -1: if click_first: self.find_element(element).click() if clear_first: self.find_element(element).clear() self.find_element(element).send_keys(value) else: if click_first: self.find_elements(element)[found_index].click() if clear_first: self.find_elements(element)[found_index].clear() self.find_elements(element)[found_index].send_keys(value) def scroll_to_text(self, text) -> NoReturn: """ 滾動到指定的text """ uiautomator_cmd = "new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().text(\"%s\").instance(0))" % text self.driver.find_element_by_android_uiautomator(uiautomator_cmd) def get_attribute(self, element: Tuple[str, Union[str, Dict]], attribute_name: str = 'text', found_index: int = -1) -> Optional[Union[str, Dict]]: """ 獲取元素屬性 """ if found_index == -1: return self.find_element(element).get_attribute(attribute_name) else: return self.find_elements(element)[found_index].get_attribute(attribute_name) def is_element_exist(self, element: Tuple[str, Union[str, Dict]], wait_seconds: int = 10) -> bool: """ 判斷元素是否存在 """ by = element[0] value = element[1] try: if by == "id": WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.ID, value))) elif by == "name": WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.NAME, value))) elif by == "class": WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.CLASS_NAME, value))) elif by == "text": WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.LINK_TEXT, value))) elif by == "partial_text": WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.PARTIAL_LINK_TEXT, value))) elif by == "xpath": WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.XPATH, value))) elif by == "css": WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, value))) elif by == "tag": WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.TAG_NAME, value))) else: raise NameError("Please enter the correct targeting elements,'id','name','class','text','xpath','css'.") except: return False return True def is_text_exist(self, text: str, wait_seconds: int = 10) -> bool: """ 判斷text是否於當前頁面存在 """ for i in range(wait_seconds): if text in self.driver.page_source: return True time.sleep(1) return False def quit(self) -> NoReturn: """ 退出驅動 """ self.driver.quit()

作者:酌三巡

分享不易,轉載請註明出處!