使用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']