Appium- Pageobject设计模式(1-3)——简介和实践capabalility封装、common公共类封装、logging模块封装

Pageobject设计模式简介

是selenium自动化测试项目开发事件的最佳设计模式之一,通过对界面元素的封装减少容易代码,同时在后期维护中,若元素定位发生变化,只需要调整页面元素封装的代码,提高测试用例的可维护性。

优化思路:

  1. 将公共的内容抽离出来,例如检测元素是否存在
  2. 将元素定位方法和元素属性值与业务代码分离
  3. 登录功能或初始化功能封装为一个独立的模块
  4. 使用unittest进行用例综合管理

 

 Pageobject实践(1)-capabalility封装

脚本实现:封装desired_caps.py:

#!urs/bin/python
#!_*_ coding:UTF-8 _*_
from appium import webdriver
import yaml
import  logging
import logging.config
#日志配置文件
CON_LOG='log.conf'
logging.config.fileConfig(CON_LOG)
logging=logging.getLogger()
def app_desired():
    #读取配置文件的数据
    file = open('cap.yaml', 'r')
    data = yaml.load(file)
    logging.info("Initialize  APP...")
    desired_caps = {}
    desired_caps['platformName'] = data['platformName']
    desired_caps['platformVersion'] = data['platformVersion']
    # 第一个模拟器默认127.0.0.1:62001  第二个默认:127.0.0.1:62025
    desired_caps['deviceName'] = data['deviceName']
    desired_caps['app'] = data['app']
    desired_caps['packageName'] = data['packageName']
    desired_caps['appActivity'] = data['appActivity']
    desired_caps['noReset'] = data['noReset']
    desired_caps['unicodekeyboard'] = data['unicodekeyboard']
    desired_caps['resetkeyboard'] = data['resetkeyboard']
    desired_caps['uiautomationName'] = data['uiautomationName']
    logging.info("Start APP...")
    driver = webdriver.Remote('http://' + str(data['ip']) + ':' + str(data['port']) + '/wd/hub', desired_caps)
    driver.implicitly_wait(8)
    return driver


#调试当前脚本方法
 

if __name__ == '__main__':
    app_desired()

Pageobject实践(2)-公共类封装

封装基类:初始化、元素定位的封装baseView.py

class BaseView(object): #继承object基类

    def __init__(self,driver): #初始化driver

        self.driver=driver

    #普通元素定位

    def find_element(self,*loc):#

        return self.driver.find_element(*loc)

    def find_elements(self, *loc):  #find_elements一般在定义list元素时使用

        return self.driver.find_elements(*loc)

#获取屏幕大小

    def getsize(self):

        return self.driver.getsize()

#滑动屏幕

    def swipe(self, star_x,star_y,end_x,end_y,duration):

        return self.driver.swipe( star_x,star_y,end_x,end_y,duration)
 

备注:*loc:其中loc表示locatioon

封装通用公共类:common_fun.py

#!urs/bin/python

#!_*_ coding:UTF-8 _*_

#从baseView.py文件内导入基类BaseView

from baseView import BaseView

from selenium.common.exceptions import NoSuchElementException

import logging

from selenium.webdriver.common.by import By

#从desired_caps .py文件内导入app_desired

from desired_caps import app_desired

import time

import os

#定义类

class Common(BaseView):

    #定义"流量充值"按钮元素

    image_button=(By.ID,"com.mydream.wifi:id/tvAsk")

    #定义元素的函数(操作)

    def check_imagebutton(self):

        logging.info("========检测元素========")

        try:

            element=self.driver.find_elements(*self.image_button)

        except NoSuchElementException:

            logging.info("========元素不存在========")

        else:

           # element.click()

            logging.info("========元素存在========")

   #定义获取屏幕的方法

    def getsize(self):

        logging.info("========获取屏幕大小========")

        x = self.driver.get_window_size()['height']  # 获取屏幕的高度

        y = self.driver.get_window_size()['width']  # 获取屏幕的宽度

        return (x, y)

    #定义向左滑动的方法

    def swipleft(self,):

        logging.info("========滑动引导页========")

        gs = self.getsize()

        x1 = int(gs[0] * 0.75)

        y1 = int(gs[1] * 0.5)

        x2 = int(gs[0] * 0.25)

        self.driver.swipe(x1, y1, x2, y1, 1000)

    def screenshot(self):

        logging.info("========屏幕截图========")

        self.driver.save_screenshot()

    #获取系统当前时间的方法

    def getTime(self):

        self.now = time.strftime("%T-%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初始化

    driver=app_desired()  #定义要启动的app

    com=Common(driver)   #定义对象

    com.check_imagebutton()

    com.swipleft()

    com.getScreenShot("star APP")


 PageObject实践(3)-logging模块封装

新建loginview.py文件,脚本内容如下:

from desired_caps import app_desired
from common_fun import Common
from selenium.webdriver.common.by import By
import logging
from time import sleep
class LoginView(Common):
    username_type=(By.ID,'com.mydream.wifi:id/cacetMobile')
    password_type=(By.ID, 'com.mydream.wifi:id/cacetPwd')
    loginBtn=(By.ID, 'com.mydream.wifi:id/cbtnLogin')
         weTab=(By.XPATH,'/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/'
                    'android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/'
                    'android.widget.TabHost/android.widget.LinearLayout/android.widget.TabWidget/android.widget.RelativeLayout[3]')
    login_type=(By.ID,'com.mydream.wifi:id/cbtnLogin')
    more_type=(By.ID,'com.mydream.wifi:id/title_third_login_button')
    def login_action(self,username,password):
        #检验首页页面元素是否存在,若存在,则可执行下面的操作
        self.check_imagebutton()
        logging.info("========切换到我的tab页面========")
        self.driver.find_element(*self.weTab).click()
        logging.info("========进入登录页面========")
        self.driver.find_element(*self.login_type).click()
        logging.info("========进入账号密码登录页面========")
        self.driver.find_element(*self.more_type).click()
        logging.info("========输入账号和密码========")
        logging.info("账号是: %s" % username)
        self.driver.find_element(*self.username_type).send_keys(username)
        logging.info("密码是: %s" % password)
        self.driver.find_element(*self.password_type).send_keys(password)
        logging.info("========开始登录========")
        self.driver.find_element(*self.loginBtn).click()
        logging.info("========登录成功========")
        sleep(5)
        self.driver.save_screenshot("login.png")


if __name__ == '__main__':
    driver = app_desired()
    #logview继承Common,Common继承BaseVIew,BaseVIew要求传入参数
    l=LoginView(driver)
    l.login_action("18059869253","123456")

备注:LoginView也是继承公共类Common、导入启动模块app_desired、导入公共类Common、导入BY元素定位模块

 

猜你喜欢

转载自blog.csdn.net/Teamo_mc/article/details/83178556
今日推荐