python+pytest+uiautomator2+allure移动端测试(五)

216 阅读2分钟

u2的基本操作继续封装的好处就是在于架构替换第三方库时直接替换咱封装的底层可以达到目的(比如uiautomator2替换成appium)

BasePage中续写方法(想法)

  1. 直接封装一个查找元素的方法,其他点击、长按、输入等操作再调取这个方法
  2. 在查找到元素或未查找到该元素时打印该步骤信息到咱自定义log中
  3. 在未找到该元素时,保存截图、打印log、报异常
  4. 截图暂时先放到查找元素异常中(在长时间运行时,需要判断某一界面不存在的,也会截图,感觉有点没必要)

查找元素

   :param attribute:元素属性名称key
   :param value: 元素属性值
   :return: 定位到的元素
def loction(self,attribute,value):
    try:
        if attribute == 'text':
            return self.deviceA(text=value)
        elif attribute == 'resourceId':
            return self.deviceA(resourceId=value)
        elif attribute == 'description':
            return self.deviceA(description=value)
        logger.debug(f'获取的元素信息:{value},获取的元素对象:{attribute},元素定位成功')
    except Exception as e:
        self.screenshot(value)
        logger.error(f'获取的元素信息:{value},获取的元素对象:{attribute},元素定位失败')

        raise e

向上滑动(解锁)

# 向上解锁滑动
def swipe_up(self):
    size = self.deviceA.window_size()
    x1 = int(size[0]*0.5)
    y1 = int(size[1]*1)
    y2 = int(size[1]*0.3)
    self.swipe_up(x1,y1,x1,y2)

灭亮屏

#灭亮屏
def power(self,kind:str = 'on or off'):
    try:
        if kind == 'on':
            self.deviceA.screen_on()
        elif kind == 'off':
            self.deviceA.screen_off()
    except Exception as e:
        logger.debug(f'获取的元素信息:{kind},灭亮屏操作失败')
        raise e

加了返回操作,在某个异常界面时能回到初始位置

# 返回
def back(self):
    try:
        self.deviceA.press('back')
    except Exception as e:
        logger.debug("返回")
        raise e

截图写在这个py文件,log写在单独文件中,因为截图需要调用设备的screenshot

根据时间戳以及元素属性命名,存放在log文件夹指定位置中,通过读取显示到allure报告中

def screenshot(self,value):
    date_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    screenshot = "%s_%s.PNG" % (date_time, value)
    imgpath = os.path.join(image_path, screenshot)
    img = self.deviceA.screenshot()
    img.save(imgpath)
    #读取指定目录下文件
    with open(imgpath, mode='rb') as f:
        file = f.read()
    allure.attach(file, value, allure.attachment_type.PNG)
    return screenshot

封装写完了,剩下的就只剩log与测试用例,其他的pom写法只需要写个页面,将操作步骤根据页面单独封装后,将元素单独提取出来。 开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 4天