一点啰嗦:发送邮件python中有另一个支持的第三方库yagmail更轻量级,代码参考可移步至此:https://www.cnblogs.com/princessironfan/p/13220601.html

 

1.封装邮件发送模块,如下:

 emailUtil.py

'''
email模块负责构造邮件内容
smtplib模块负责发送邮件
'''
import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from email.header import Header

from common.logger_handler import file_logger


class sendEmail():
    MAILHOST = "smtp.qq.com"
    MAILUSER = "XXXX@qq.com"
    MAILPWD = "授权码"

    def __init__(self, subject, content, reveiver, attachPath=""):
        """
        :param subject: 邮件主题
        :param content: 邮件正文
        :param reveiver: 收件人
        :param attachPath: 测试报告的路径
        """
        self.subject = subject
        self.content = content
        self.receiver = reveiver
        self.attachPath = attachPath

    # 写邮件,返回msg.as_string()
    def writeEmail(self):
        msg = MIMEMultipart()
        # 邮件正文
        msg.attach(MIMEText(self.content, 'plain', 'utf8'))
        receiverName = ",".join(self.receiver)
        msg['from'] = Header(self.MAILUSER, 'utf-8')
        # msg['to'] =  Header(",".join(self.receiver)).encode()
        msg['to'] = Header(receiverName).encode()
        # 邮件主题
        msg['Subject'] = Header(self.subject, 'utf-8').encode()
        # print("msg is:",msg)
        # attachPath不为空则添加附件到邮件中
        if self.attachPath != "":
            with open(self.attachPath, 'rb') as f:
                attach1 = MIMEText(f.read(), 'base64', 'utf-8')
                attach1["Content-Type"] = 'application/octet-stream'
                # filename自己命名
                now_time = datetime.datetime.now().strftime('%Y_%m_%d %H_%M_%S')
                attach1["Content-Disposition"] = 'attachment; filename="apiReport_{}.html"'.format(now_time)
                msg.attach(attach1)

        return msg.as_string()

    # 发送邮件
    def sendEmail(self):
        receiver = ";".join(self.receiver)
        try:
            # 连接邮件服务器
            server = smtplib.SMTP()
            server.connect(self.MAILHOST, 25)
            # 打开debug模式可以看到握手过程
            # server.set_debuglevel(1)
            # 登录,MAILPWD为邮件的授权码
            server.login(self.MAILUSER, self.MAILPWD)
            # 发送邮件
            server.sendmail(self.MAILUSER, receiver, self.writeEmail())
            server.quit()
            file_logger.warning("Email send sucess.")
        except Exception as e:
            file_logger.warning("Email send fail.")
            file_logger.warning(e)

 

2. 运行测试用例模块代码:

run_test.py

from common.config_path import config_path
from libs import HTMLTestRunnerNew
import unittest

def all_ceses_suite():
    test_loader = unittest.TestLoader()  # 初始化
    suite = test_loader.discover(config_path.cases_data)  # 测试用例加载
    return suite


class SendEmail:
    def __init__(self, module, email="null"):
        self.module = module
        self.email = email

    def send_to(self):
        now_time = datetime.datetime.now().strftime('%Y_%m_%d %H_%M_%S')  # 获取当前时间
        file_path = os.path.join(config_path.report_path, "ApiReport_{}.html".format(now_time))  # 存放测试报告的文件夹
        with open(file_path, "wb") as f:
            runner = HTMLTestRunnerNew.HTMLTestRunner(f, verbosity=2,
                                                      title="接口自动化测试报告")
            result = runner.run(self.module)

            totalNums = self.module.countTestCases()
            passedNums = result.success_count
            failedNums = result.failure_count
            errorNums = result.error_count
            skippedNums = len(result.skipped)
            # 通过率,保留两位小数
            passRate = round(passedNums * 100 / totalNums)
       
       Construction_results = "本次构建一共运行:{}个用例,通过{}个,失败{}个,错误{}个,跳过{}个。通过率:{}%".format(totalNums, passedNums,
failedNums, errorNums,skippedNums, passRate)
       # print(Construction_results)

       if passRate != 100: # 判断有失败用例时执行发送邮件,若需要每次执行完成便发送邮件,则去掉此判断   get_receiver=['xxxx@qq.com']   emailBody = "\n \t{}\n \t详细信息请查看附件。 ".format(Construction_results)   content = emailBody.format(totalNums=totalNums, passedNums=passedNums, failedNums=failedNums, errorNums=errorNums, skippedNums=skippedNums, passRate=passRate)   subject = "接口测试"   # 发送邮件   if len(get_receiver) > 0:   for i in get_receiver:   receiver = [i]   e = sendEmail(subject, content, receiver, attachPath=file_path)   e.sendEmail() if __name__ == '__main__': # 所有用例 all = SendEmail(all_ceses_suite()) all.send_to()

做一棵小草,谁也撼动不了………

 

 

posted on 2020-07-01 16:53  小草小草随风飘摇  阅读(377)  评论(0编辑  收藏  举报