import unittest
import os
from cases.api_case import Apicases #從case目錄下的api_case文件中導入Apicases這個類
from HTMLTestRunner import HTMLTestRunner
import time
import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
#獲取當前時間
now = datetime.datetime.now()
#轉換為指定格式
OtherStyleTime = now.strftime('%Y-%m%d %H:%M:%S')
#創建測試套件
suite = unittest.TestSuite()
#添加測試用例
cases = [Apicases('test_1_login'),Apicases('test_2_token'),Apicases('test_3_employeeId'),Apicases('test_4_team')]
#繼承測試報告
report_name = '接口自動化測試報告'
report_title = '接口測試報告' + OtherStyleTime
report_des = '接口測試報告描述' + '測試時間是' + OtherStyleTime
report_path = './report'
report_file = report_path + '.html' #測試報告名字(要加時間戳只能在'report.html'之前加,如:report_path + now + 'report.html')
#判斷文件夾是否存在
if not os.path.exists(report_path):
os.mkdir(report_path)
else:
pass
with open(report_file,'wb') as report:
suite.addTests(cases)
runner = HTMLTestRunner(stream=report,title=report_title,description=report_des)
runner.run(suite)
print(11111111111111)
#第三方SMTP服務
mail_host = 'smtp.qq.com' #設置qq服務器
mail_user = '602***19@qq.com' #用戶名
mail_pass = 'zsgkpfmydebkbfbj' #,密碼(授權碼)
sender = '602***619@qq.com' #發送者郵箱
receivers = ['w**an@nlelpct.com','60***19@qq.com'] #接受者郵箱
#讀取html文件的內容
f = open("./report.html",'rb')
mail_body = f.read()
f.close()
#讀取的HTML 形式的文件內容做為郵件的正文主題
html = MIMEText(mail_body,'html','utf-8') #郵件正文內容,plain:默認的寫文本形式郵件的格式,如發送的是HTML,則plain改成HTML
# HTML附件 將測試報告放在附件中發送
att1 = MIMEText(mail_body,'base64','gb2312')
att1['Content-Type'] = 'application/octet-stream'
att1['Content-Disposition'] = 'attachment; filename = "lwy_aototest_report.html"' #filename是指下載的附件的命名
msg = MIMEMultipart()
msg.attach(html) #將html附加在msg里
msg.attach(att1) #新增一個附件
msg['Subject'] = 'lwy_自動化測試報告' #定義郵件主題
msg['From'] = Header('lwy_自動化測試報告','utf-8') #發送者
msg['To'] = Header('信息中心','utf-8') #接收者
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host,25) #25是SMTP的端口號
smtpObj.login(mail_user, mail_pass) #登錄郵箱
#SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])
smtpObj.sendmail(sender,receivers,msg.as_string()) # ***.as_string()--***指的是郵件的各個主題、發送者
print('郵件發送成功')
except smtplib.SMTPException:
print('error:無法發送郵件')
運行結果