Python+Appium自动化测试(14)-yaml配置Desired capabilities
一,前言
在之前的appium自动化测试示例中,我们都是把构造driver实例对象的数据(即Desired Capabilities)写在业务代码里,如下:
# -*- coding:utf-8 -*-
# @author: 给你一页白纸
from appium import webdriver
desired_caps = {
"platformName": "Android",
"platformVersion": "10",
"deviceName": "PCT_AL10",
"appPackage": "com.ss.android.article.news",
"appActivity": ".activity.MainActivity",
"automationName": "UiAutomator2",
"unicodeKeyboard": True,
"resetKeyboard": True,
"noReset": True,
}
driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
这种情况下,如果我们要更换测试机测试的话,就需要去代码里面修改这些信息,从项目维护的角度来说显然是不方便的,应该考虑将这些测试配置信息写在专门的配置文件里,使用的时候直接调用即可。
二,使用yaml文件配置Capabilities示例
目录结构如下:
config下的desired_caps.yml文件里capabilities数据如下(Python中yaml文件的读写方法点这里):
platformName: Android
platformVersion: '10'
deviceName: PCT_AL10
appActivity: .activity.MainActivity
appPackage: com.ss.android.article.news
automationName: UiAutomator2
resetKeyboard: true
noReset: true
unicodeKeyboard: true
ip: 127.0.0.1
port: 4723
common下的baseDriver.py文件中构造driver的函数如下:
# -*- coding:utf-8 -*-
# @author: 给你一页白纸
import yaml, os
from appium import webdriver
# 项目根目录路径,即android-ui-autotest文件夹的路径
BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# capabilities配置文件desired_caps.py路径
DESIRED_CAPS_YAML_PATH = CONFIG_PATH + '/config/desired_caps'
def android_driver():
# 从desired_caps.yaml读取driver配置数据
stream = open(DESIRED_CAPS_YAML_PATH, 'r')
data = yaml.load(stream, Loader=yaml.FullLoader)
desired_caps = {}
desired_caps['platformName'] = data['platformName']
desired_caps['platformVersion'] = data['platformVersion']
desired_caps['deviceName'] = data['deviceName']
desired_caps['appPackage'] = data['appPackage']
desired_caps['appActivity'] = data['appActivity']
desired_caps['automationName'] = data['automationName']
desired_caps['unicodeKeyBoard'] = data['unicodeKeyBoard']
desired_caps['resetKeyboard'] = data['resetKeyboard']
desired_caps['noReset'] = data['noReset']
driver = webdriver.Remote('http://' + str(data['ip']) + ':' + str(data['port']) + '/wd/hub', desired_caps)
driver.implicitly_wait(8)
return driver
三,更新yaml文件的内容
有时候我们需要通过脚本修改yaml文件里的配置信息。比如更换了测试机,capabilities里的platformVersion、deviceName都变了,脚本自动获取新测试机的这两个参数,并更新至desired_caps.yml文件里。
更新yaml文件思路:
1,先读取需要更新的yaml文件的内容;
2,将读取内容里需要更改内容替换成新的内容;
3,再写入yaml文件。
示例代码如下:
# -*- coding:utf-8 -*-
# @author: 给你一页白纸
import yaml
def update_yaml():
with open('./config/desired_caps', 'r', encoding='utf-8') as f:
content = yaml.load(f, Loader=yaml.FullLoader)
content['platformVersion'] = 'newPlatformVersion'
content['deviceName'] = 'newDeviceName'
with open('./config/desired_caps', 'w', encoding='utf-8') as nf:
yaml.dump(data=content, stream=nf, allow_unicode=True)