本文主要介绍完整构建针对andorid项目构建appium自动化的过程,万事开头难,相信读完此文可以让你少踩几个坑。(如有错误,敬请留言)
1、下载appium应用程序
2、创建virtualenv,安装Appium-Python-Client
mkdir projectName
virtualenv venv
. venv/bin/activate
pip3 install appium-python-client==0.52
此处应注意appium-python-client的安装版本应与appium-desktop相对应,如果遇到以下错误,基本就是版本不匹配造成的
selenium.common.exceptions.WebDriverException: Message: Parameters were incorrect. We wanted {"required":["desiredCapabilities"],"optional":["requiredCapabilities","sessionId","id"]} and you sent ["capabilities","desiredCapabilities"]
3、根据要测试的手机和app来完成初始化配置(指定chromedriverExecutableDir可以解决手机端chrome和当前安装的chromedriver版本不匹配问题,可以根据手机chrome版本选择下载对应的chromedriver,将可执行文件放置在相关目录)
capabilities:
platformName: android
platformVersion: 8.1.0 # check the andorid version of the device
udid: xxxxxxxxxxxx # use commend adb devices to get this value
newCommandTimeout: 600
appPackage: xxxxxxxxxxxxx # use aapt dump badging *.apk and get the package name
chromedriverExecutableDir: xxxxxxxxxxxxx # the directory of chromedriver execute file
appActivity: xxxxxx # commend aapt dump badging *.apk and get the launchable-activity
deviceName: xxxxxxxxxxxxxxxxx
4、获取driver
def get_desired_capabilities():
with open("Application.yaml", "r") as f:
content = f.read()
config = yaml.safe_load(content)
desired_caps = {'platformName': config['capabilities']['platformName'],
'platformVersion': config['capabilities']['platformVersion'],
'udid': config['capabilities']['udid'],
'newCommandTimeout': config['capabilities']['newCommandTimeout'],
'appPackage': config['capabilities']['appPackage'],
'chromedriverExecutableDir': config['capabilities']['chromedriverExecutableDir'],
'appActivity': config['capabilities']['appActivity'],
'deviceName': config['capabilities']['deviceName']}
return desired_caps
def get_driver():
desired_caps = get_desired_capabilities()
driver = webdriver.Remote(command_executor="http://127.0.0.1:4723/wd/hub", desired_capabilities=desired_caps)
return driver
5、usb连接手机,运行appium desktop,就可以开始编写测试程序了,获取元素的过程中可能存在页面跳转慢或其他原因出现异常,笔者在程序所有获取元素的地方中加了一个小注解。
def timeout_limit(get_element_method):
def get_element(*args, **kwargs):
origin_time = int(time.time())
while True:
try:
element = get_element_method(*args, **kwargs)
except Exception as e:
element = None
if element and element.is_displayed():
return element
else:
time.sleep(2)
current_time = int(time.time())
if current_time - origin_time > 15:
print("time out to get element")
return None
return get_element