34、Selenium + Python 实现 UI 自动化测试-正片6

某一天,测试地址变了。或者某一天邮件发送和接收人地址变了,怎么办?我们需要去login.py文件中修改url地址;我们需要去sendmail.py文件中修改邮件发送和接收人地址。去不同文件修改不同变量值,对于不熟悉你框架的人来说是困难的,对于我们自己来说也是不方便的。


今天我们引入配置文件,将这些易发生变化的部分,放到配置文件里,做统一管理。

一、我们在框架目录下,新建config文件夹,用来存储项目配置文件。

1、新建文件config.yaml,内容如下:


# url 配置
url: http://localhost:81/redmine/login
# mail 相关配置
host: smtp.163.com
sender: [email protected]
passwd: xxxxxxx
receiver: [email protected]
subject: 测试主题,按需修改
contents: 邮件内容,按需修改
上面使用yaml 作为配置文件格式,后面我们再介绍其他格式的使用方法。

注意,冒号后面必须有一个空格,冒号前面可以没有空格;没有双引号或单引号。

#为注释符


2、接下来我们需要写一个函数或类,来读取yaml文件。

import yaml
import os

def read_yaml(info):
    base_path = os.path.dirname(os.path.abspath(__file__))
    conf_path = base_path + '\..\config\config.yaml'
    with open(conf_path,'r',encoding='utf-8') as f:
        return yaml.load(f).get(info)

if __name__ == '__main__':
    url = read_yaml('url')
    print(url)
    host = read_yaml('host')
    print(host)

3、修改test_000_login.py、login.py 和 sendmail.py

以sendmail.py为例:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from first.run import reportdir
from first.utils import readyaml

def sendmail():
    host = readyaml.read_yaml('host')
    sender = readyaml.read_yaml('sender') #发送方邮件地址
    passwd = readyaml.read_yaml('passwd')              #发送方密码
    receiver = readyaml.read_yaml('receiver')  #接收报告方邮件地址

    msg = MIMEMultipart()
    msg['from'] = sender
    msg['to'] = receiver
    msg['subject'] = readyaml.read_yaml('subject')
    msg.attach(MIMEText(readyaml.read_yaml('contents')))

    att1 = MIMEText(open(reportdir, 'rb').read(), 'base64', 'utf-8')
    att1["Content-Type"] = 'application/octet-stream'
    # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
    att1["Content-Disposition"] = 'attachment; filename="report.html"'
    msg.attach(att1)

    try:
        smtpobj = smtplib.SMTP(host, port=25)
        smtpobj.login(sender, passwd)
        smtpobj.sendmail(sender, receiver, msg.as_string())
        smtpobj.quit()
        print('send success')
    except:
        print('send err')

if __name__ == '__main__':
    sendmail()

然后试运行 run.py,成功。

这个时候尝试修改下配置文件中的邮件主题和邮件内容,再次运行,看收到的新邮件主题和内容是否变化。


好,简单总结一下:

1、为了使程序更易读,我们将代码和配置相分离,单独保存配置文件,本文引入 yaml 格式作为配置文件

2、你也可以使用ini、json、cvs、 properties等格式。(后面我们也会一一讲解)


你可能感兴趣的:(Selenium,+,Python)