背景和目的
目的:安卓ui自动化测试中,根据每次连接的手机设备不同,而自动生成不同的数据配置文件
在做安卓ui自动化测试时,yaml 文件一般放测试的数据或当配置文件使用,yaml 文件存放静态的数据是没问题的,python的数据类型基本上都是支持的。
但是多台设备并行时需要根据设备的uuid分配指定的一套测试数据,这时设备的uuid就作为变量被读取和赋值。
template使用
template 是字符串模板,用于替换字符串中的变量,是 string 的一个类引用变量有 2 种格式
- 第一种 $variable
from string import Template
tempTem = Template("My name is $name , i like $fancy")
d = {'name': 'admin', 'fancy': 'python'}
print(tempTem.substitute(d))
- 第二种 ${variable}
from string import Template tempTemp1 = Template("My name is ${name} , i like ${fancy}") d = {'name': 'admin', 'fancy': 'python'} print(tempTemp1.substitute(d))
yaml 模板文件给变量赋值再另写yaml
思路
- data文件夹作为自动化测试的数据驱动层
- checkin_data_template.yaml为测试模板
udids:
udid0: $udid0
udid1: $udid1
mobile_login_data:
$udid0:
# 普通用户
mobile_num: 13007135437
login_psw: 123456
$udid1:
# 普通用户
mobile_num: 13007135437
login_psw: 123456
- checkin_data.yaml为根据每次连接的手机不同,而生成不同的数据配置文件
- 实现后的效果如下,这样就可以不用每次都改yaml文件了!
udids:
udid0: 192.168.38.32:60176
udid1: 192.168.38.32:60723
mobile_login_data:
192.168.38.32:60176:
mobile_num: 13007135437
login_psw: 123456
192.168.38.32:60723:
mobile_num: 13007135437
login_psw: 123456
具体实现
tmp_read = f.read()
tmp_read_template = Template(tmp_read)
tmp_target_yaml = tmp_read_template.safe_substitute(target_dict)
tmp_target_python = yaml.safe_load(tmp_target_yaml)
- 先读取yaml模板文件checkin_data_template.yaml,然后使用safe_substitute给变量赋值,最后将结果转为python格式
yaml.dump(tmp_target_python, f, allow_unicode=True, sort_keys=False)
- 然后将python格式的文件,转换成不排序的yaml文件
# 根据yaml模板生成本次自动化yaml模板
def create_target_yaml(target_dict):
'''
target_dict:{"udid0": 1111, "udid1": 2222}
'''
if os.path.dirname(os.path.dirname(__file__)) == config_data.ROOT_DIR:
yaml_data_path = os.path.dirname(os.path.dirname(__file__)) + '/data' + '/checkin_data_template.yaml'
else:
yaml_data_path = os.path.dirname(__file__) + '/data' + '/checkin_data_template.yaml'
with open(yaml_data_path, encoding="utf-8") as f:
tmp_read = f.read()
tmp_read_template = Template(tmp_read)
tmp_target_yaml = tmp_read_template.safe_substitute(target_dict)
tmp_target_python = yaml.safe_load(tmp_target_yaml)
if os.path.dirname(os.path.dirname(__file__)) == config_data.ROOT_DIR:
yaml_data_path = os.path.dirname(os.path.dirname(__file__)) + '/data' + '/checkin_data.yaml'
else:
yaml_data_path = os.path.dirname(__file__) + '/data' + '/checkin_data.yaml'
with open(yaml_data_path, 'w', encoding="utf-8") as f:
# 不排序
yaml.dump(tmp_target_python, f, allow_unicode=True, sort_keys=False)