自动化测试需要做到代码和数据分离,我们经常需要将不同的数据放到不同的文件内进行读取,比如用例放到Excel表里,配置文件放到ini文件里等等。yaml专门用于写配置文件
pip install pyyaml
yaml文件,test.yaml
user: admin
pwd: 123456
#! /usr/bin/python3
# -*- coding:utf-8 -*-
# @Time : 2020/8/17 9:23
# @Author : 码上开始
import yaml
# 定义yaml文件路径
yaml_path = "E:\\study\\date.yaml"
# 打开yaml文件
file = open(yaml_path, "r", encoding="utf-8")
# 读取
string = file.read()
dict = yaml.load(string)
# 转换后数据类型为:dict
print(type(dict))
print(dict)
# 运行结果:
{'usr': 'admin', 'pwd': 123456}
- admin1
- admin2
- admin3
#! /usr/bin/python3
# -*- coding:utf-8 -*-
# @FileName: day6.py
# @Time : 2020/8/17 9:23
# @Author : 码上开始
import yaml
# 定义文件路径
yaml_path = "E:\\study\\date.yaml"
file = open(yaml_path, "r", encoding="utf-8")
string = file.read()
print(string)
# 转换后数据类型为列表
list = yaml.load(string, Loader=yaml.FullLoader)
print(list)
# 运行结果
<class 'list'>
['admin1', 'admin2', 'admin3']
# 布尔值true/false
n: true
# int
n1: 12
# float
n2: 12.3
# None
n3: ~
{'n': True, 'n1': 12, 'n2': 12.3, 'n3': None}
- usr:
name: admin
pwd: 123456
- mail:
user: [email protected]
pwd: 123456
运行结果:
[{'usr': {'name': 'admin', 'pwd': 123456}}, {'mail': {'user': '[email protected]', 'pwd': 123456}}]
#! /usr/bin/python3
# -*- coding:utf-8 -*-
# @Time : 2020/8/17 9:23
# @Author : 码上开始
import yaml
写入键值对
# data = {"send_mail": "[email protected]"}
# 写入列表
# data =["[email protected]", "[email protected]"]
# 写入混合数据
# data = [{"mai": {"send": "[email protected]"}}]
# yaml文件路径
yaml_path = "E:\\study\\date.yaml"
# 打开文件,a是在文件末尾写入内容
file = open(yaml_path, "a", encoding="utf-8")
# 写入数据, allow_unicode=True
yaml.dump(data, file)
# 关闭文件
file.close()
运行结果
# 键值对
send_mail: [email protected]
# 列表
- [email protected]
- [email protected]
# 混合数据
- mai:
send: [email protected]
上面我们说了yaml用于在自动化测试中实现代码和数据分离。那么我们在企业项目中如何用yaml实现代码和数据分离呢?有一个场景,我们要发送邮件给指定收件人。
# 发件人邮箱和授权码
- send_mail: [email protected]
password: QQ邮箱的授权码
# 收件人邮箱
- get_mail: [email protected]
#! /usr/bin/python3
# -*- coding:utf-8 -*-
# @FileName: read_yaml.py
# @Time : 2020/8/19 16:21
# 公众号 : 码上开始
import yaml
def read_yaml():
"""读取yaml文件"""
# 定义yaml文件路径
yaml_path = "E:\\mail\\date\\yaml.yaml"
# 打开yaml文件
file = open(yaml_path, "r")
# 读取文件
string = file.read()
# 转换为python对像,类型为字典
dict = yaml.load(string)
print(dict)
# 返回数据为字典类型
return dict
运行结果
[{'send_mail': '[email protected]', 'password': 'code'}, {'get_mail': '[email protected]'}]
#! /usr/bin/python3
# -*- coding:utf-8 -*-
# @FileName: mail.py
# @Time : 2020/8/19 16:20
# 公众号 : 码上开始
import zmail
# 导入common文件下的read_yaml函数
from common import read_yaml
# 调用yaml文件里的数据
response = read_yaml.read_yaml()
def send(send_mail, password, get_mail):
"""发送测试报告"""
report_path = "E:\\mail\\report\\test.html"
MAIL = {
'subject': '邮件主题',
'content_text': '测试发送邮件',
'attachments': report_path,
}
server = zmail.server(send_mail, password)
server.send_mail(get_mail, MAIL)
send(response[0]["sendmail"], response[0]["password"], response[1]["getmail"])