1. 程式人生 > >Appium--pageobject實踐(4)-unittest封裝

Appium--pageobject實踐(4)-unittest封裝

前提:已配置好yaml應用初始化引數檔案和log.conf日誌配置檔案

定義配置檔案cap.yaml,包括key和value,具體內容如下:

platformName: Android 
platformVersion: 4.4.2 
deviceName: 127.0.0.1:62001 
app: apk檔案路徑
packageName: 包名 
appActivity: 主Activity 
unicodekeyboard: True 
resetkeyboard: True 
noReset: False 
ip: 127.0.0.1 
port: 4723 
uiautomationName: uiautomator2

定義日誌配置檔案logconf,指令碼內容如下:

[loggers]

keys=root,main

[logger_root]

level=DEBUG

handlers=consoleHandler,fileHandler

[logger_main]

level=DEBUG

qualname=main

handlers=fileHandler

[handlers]

keys=consoleHandler,fileHandler

[handler_consoleHandler]

class=StreamHandler

level=DEBUG

formatter=fmt

args=(sys.stdout,)

[handler_fileHandler]

class=logging.handlers.RotatingFileHandler

level=DEBUG

formatter=fmt

args=('test.log','a')

[formatters]

keys=fmt

[formatter_fmt]

format=%(asctime)s - %(filename)s - %(levelname)s - [line:%(lineno)d] - %(message)s

建立啟動app初始化模組:新建desired_caps.py檔案,指令碼內容如下

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()

 

建立基類,新建baseview.py檔案,指令碼內容如下:

class BaseView(object):

    def __init__(self,driver):

        self.driver=driver

    #普通元素定位

    def find_element(self,*loc):

        return self.driver.find_element(*loc)

    #元素定位返回一個數組list,一般用於判斷元素是否存在

    def find_elements(self,*loc):

        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)



    def time_wait(self,t):

        return self.sleep(t)

 

建立公共類,建立lijitiyan.py檔案,指令碼內容如下:

 
#!urs/bin/python

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

#從baseView.py檔案內匯入基類BaseView

from baseView import BaseView

from selenium.common.exceptions import NoSuchElementException

import logging

import time

from selenium.webdriver.common.by import By

#從desired_caps .py檔案內匯入app_desired

from desired_caps import app_desired

from time import sleep

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_element(*self.image_button)

        except NoSuchElementException:

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

        else:

           # element.click()

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

    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()

    com=Common(driver)

    com.check_imagebutton()

    com.getScreenShot("star APP")




 

建立登陸模組指令碼,建立loginView.py檔案,指令碼內容如下:

from desired_caps import app_desired

from common_fun import Common

from lijitiyan 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")

建立myunit.py檔案,指令碼內容如下:

import unittest
import logging
from desired_caps import app_desired
from time import sleep
class StarEnd(unittest.TestCase):
    #啟動app
    def setUp(self):
        logging.info("========setUp========")
        self.driver=app_desired()
    def tearDown(self):
        logging.info("========tearDown========")
        sleep(5)
        self.driver.close_app()  #呼叫退出app的方法

建立test_unit.py,指令碼內容如下:

from myunit import StarEnd

from loginView import LoginView #匯入已封裝好的登陸模組

import unittest

import logging



class TestLogin(StarEnd):   #繼承myunit.py檔案內的StarEnd類

#測試用例必須以test開頭

    def test_login_01(self):

        logging.info("========登入成功========")

        l = LoginView(self.driver)

        l.login_action("18059869253", "123456")

    def test_login_02(self):

        logging.info("========登入密碼錯誤========")

        l = LoginView(self.driver)

        l.login_action("15280265205", "123456")



if __name__ == '__main__':

    unittest.main()