前篇我们封装了driver模块,这篇主要学习封装公共类,在封装之前我们还是要先封装基类模块。基类模块主要封装一些初始化和元素定位的基础方法。方法和我们在PageObject设计方法实践时的设计方法一致,主要是又补充了一些新的方法。如下;class BaseView(object): def __init__(self,driver): self.driver=driver
def find_element(self,*loc): return self.driver.find_element(*loc)
def find_elements(self,*loc): return self.driver.find_elements(*loc)
def get_window_size(self): return self.driver.get_window_size()
def swipe(self, start_x, start_y, end_x, end_y, duration): return self.driver.swipe(start_x,start_y, end_x, end_y, duration) 公共类模块主要存放后期我们会用到的一些公共方法,如跳过同意协议按钮、获取屏幕尺寸、向左滑动、向右滑动、向上滑动、向下滑动、获取当前时间、屏幕截图等方法。封装完成后,我们在其他模块直接调用继承common模块,用起来更方便。2、定义公共类Common,并继承BaseView类,然后在该类下定义各种方法。首先是检查同意协议的按钮,并点击。4、定义向左、向右、向上、向下的滑动方法,方便后期在需要的业务模块使用。5、定义获取当前时间的方法,并通过strftiome()方法转换时间格式,最后返回当前时间。6、定义截取屏幕的方法,并通过获取路径,拼接传入参数名和当前时间命名的图片名称,保存到指定路径下。7、在每个方法下添加日志信息。方便后期运行时定位问题。import os.path import time from common.desired_caps importappium_desired from baseView.BaseView import BaseView from selenium.common.exceptions importNoSuchElementException from selenium.webdriver.common.by import By import logging class Common(BaseView): agreeBtn = (By.XPATH, '/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.FrameLayout[2]/android.widget.LinearLayout/android.webkit.WebView/android.webkit.WebView/android.view.View/android.view.View[3]/android.view.View[10]/android.view.View[2]') def check_agreeBtn(self): logging.info('check agreeBtn') try: agreeBtn=self.driver.find_element(*self.agreeBtn) except NoSuchElementException: logging.info('no agreeBtn') else: logging.info('click agreeBtn') agreeBtn.click() def get_size(self): x = self.driver.get_window_size()['width'] y = self.driver.get_window_size()['height'] return x, y def swipeLeft(self): logging.info('swipeLeft') l = self.get_size() x1 = int(l[0] * 0.9) y1 = int(l[1] * 0.5) x2 = int(l[0] * 0.1) self.swipe(x1, y1, x2, y1, 1000) def swipeRight(self): logging.info('swipeRight') l = self.get_size() x1 = int(l[0] * 0.1) y1 = int(l[1] * 0.5) x2 = int(l[0] * 0.9) self.swipe(x1, y1, x2, y1, 1000) def swipeUp(self): logging.info('swipeUp') l = self.get_size() x1 = int(l[0] * 0.5) y1 = int(l[1] * 0.8) y2 = int(l[1] * 0.2) self.swipe(x1, y1, x1, y2, 1000) def swipeDown(self): logging.info('swipeDown') l = self.get_size() x1 = int(l[0] * 0.5) y1 = int(l[0] * 0.2) y2 = int(l[0] * 0.8) self.swipe(x1, y1, x1, y2, 1000) def getTime(self): self.now=time.strftime("%Y-%m-%d %H-%M-%S") return self.now def getScreenShot(self,module): time=self.getTime() image_file=os.path.dirname(os.path.dirname(__file__))+'/screenshots/%s%s.png' %(module,time) logging.info('get %s screenshot' %module) self.driver.get_screenshot_as_file(image_file) if __name__ == '__main__': driver=appium_desired() com=Common(driver) com.check_agreeBtn() #com.getScreenShot('startAPP') com.getScreenShot("start APP")
|