使用APPIUM框架+PYTHON腳本實現自動化(發個動態)
一、python
# -*- coding:utf-8 -*-
from time import sleep
from appium import webdriver
import pytest
import os,sys
import yaml
import allure
import logger
from appium.webdriver.common.touch_action import TouchAction
import time
path=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
file=path+"/Config/desire_caps_wx.yaml"
f=open(file,"r")
CAPS=yaml.safe_load(f)
#實例化封裝的Logger
LOG=logger.Logger("TestDemo").getlog()
class TestDemo:
def setup(self):
desired_caps={}
desired_caps['platformName']=CAPS['platformName']
desired_caps['platformVersion']=CAPS['platformVersion']
desired_caps['appPackage']=CAPS['appPackage']
desired_caps['appActivity']=CAPS['appActivity']
desired_caps['deviceName']=CAPS['deviceName']
desired_caps['noReset'] = CAPS['noReset']
#desired_caps['unicodeKeyboard']=True
LOG.info("APPIUM SERVER 啓動")
LOG.info("啓動"+desired_caps['appPackage'])
LOG.info("啓動" + desired_caps['appActivity'])
self.driver = webdriver.Remote("http://localhost:4723/wd/hub",desired_caps)
self.driver.implicitly_wait(20)
def log ( func ):
def wrapper ( *args, **kw ):
print('TEST CASE:%s' % func.__name__)
return func(*args, **kw)
return wrapper
@log
def test_publish_word(self):
self.driver.implicitly_wait(15)
self.driver.find_element_by_xpath("//*[@text='發現']").click()
self.driver.find_element_by_xpath("//*[@text='朋友圈']").click()
el3=self.driver.find_element_by_xpath("//*[@class='android.support.v7.widget.LinearLayoutCompat']")
TouchAction(self.driver).long_press(el3).perform()
el4=self.driver.find_element_by_id("com.tencent.mm:id/d41")
WORDS="hello friend"+time.asctime(time.localtime(time.time()))
el4.send_keys(WORDS)
self.driver.find_element_by_id("com.tencent.mm:id/ln").click()
reet=self.driver.find_elements_by_xpath("//*[contains(@text,WORDS)]")
assert len(reet)>0
def teardown(self):
self.driver.quit()
if __name__ == '__main__':
pytest.main(['-s', '-q', '--alluredir', './report/xml'])
f.close()
二、執行結果:
三、備註
(1)長按操作:
from appium.webdriver.common.touch_action import TouchAction
TouchAction(self.driver).long_press(element).perform()
(2)跨目錄文件路徑獲取:
os.path.abspath(__file__)#獲取當前文件絕對路徑
os.path.dirname()獲取當前文件路徑的上級目錄
os.path.dirname(os.path.dirname())獲取當前文件路徑的上上級目錄
(3)測試用例前面的@log,裝飾器
打印測試用例的名稱
def log ( func ):
def wrapper ( *args, **kw ):
print('TEST CASE:%s' % func.__name__)
return func(*args, **kw)
return wrapper
(4)assert斷言
reet=self.driver.find_elements_by_xpath("//*[contains(@text,WORDS)]")
assert len(reet)>0
(5)隱式等待
self.driver.implicitly_wait()
(6)setup()方法
啓動,測試環境初始化
(7)def teardown()方法
清理測試環境,退出driver
(8)元素定位:
driver.find_element_by_xpath()
driver_find_element_by_id()
往編輯框填寫內容:element.
sendkeys()
(9)desired_caps參數通過配置文件獲取
f=open(file,"r")
CAPS=yaml.safe_load(f)desired_caps['platformName']=CAPS['platformName']