python+selenium+unittest测试框架3-项目构建和发送邮件

 项目构建和发送邮件

一、项目构建

1、建立项目chen

打开pycharm左上角File>New Project,在Location输入testing项目所在文件夹D:chen,创建后选择Opin in current window。

2、创建子文件夹

PS:创建文件夹,一定要选Python Package的方式创建。

3、创建测试脚本

4、创建runalltest.py

 PS:在runalltest.py这个脚本里面写主函数,控制执行所有的用例。

5、下载生成测试报告的源码

import HTMLTestRunner
import unittest
import os
#测试用例存放路径
casepath = os.path.join(os.getcwd(),"case")
#测试报告存放路径
reportpath = os.path.join(os.getcwd(),"report")
def allcase():
    '''加载测试用例'''
    discover = unittest.defaultTestLoader.discover(casepath,
                                                   pattern="case*.py",
                                                   top_level_dir=None)
    return discover
def runcase():
    '''执行测试用例,生成测试报告'''
    htmlreportpath = os.path.join(reportpath,"result.html")
    fp = open(htmlreportpath,"wb")
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
                                           title=u"自动化测试报告",
                                           description=u"测试用例执行情况")
    # 调用allcase函数返回值
    runner.run(allcase())
    fp.close()

if __name__ == "__main__":
    runcase()    

二、发送邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_mail(sender, psw, receiver, smtpserver,reportfile, port=465):
    '''发送最新的测试报告内容'''
    #打开测试报告
    with open(reportfile, "rb") as f:
        mail_body = f.read()
    # 定义邮件内容
    msg = MIMEMultipart()
    body = MIMEText(mail_body, _subtype='html', _charset='utf-8')
    msg['Subject'] = u"自动化测试报告"
    msg["from"] = sender
    msg["to"] = receiver
    msg.attach(body)
    # 添加附件
    att = MIMEText(open(reportfile, "rb").read(), "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = 'attachment; filename= "report.html"'
    msg.attach(att)
    try:
        smtp = smtplib.SMTP_SSL(smtpserver, port)
    except:
        smtp = smtplib.SMTP()
        smtp.connect(smtpserver,port)
    # 用户名密码
    smtp.login(sender, psw)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()

if __name__ == '__main__':
    reportfile = u"F:\python36\test\report\result.html"#测试报告路径
    smtpserver = "smtp.qq.com"  #  邮箱服务器
    sender = "139271007@qq.com" # 自己的账号
    psw = "password" #自己的密码
    receiver = "386421542@qq.com" #对方的账号
    send_mail(sender, psw, receiver, smtpserver,reportfile)
原文地址:https://www.cnblogs.com/chen/p/8574239.html