前段时间弄一个测试框架,满足公司简单网站的测试,整合了一个函数模块,包括常用的截图、邮件发送、测试报告生成,具体代码如下
import smtplib from BSTestRunner import BSTestRunner #报告的模板,这里没用到 from email.header import Header from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import os #截图sc_image def sc_image(driver,filename): #获取当前模块所在路径 func_path=os.path.dirname(__file__) #获取test_case目录 base_dir=os.path.dirname(func_path) #将路径转化为字符串 base_dir=str(base_dir) #对路径的字符串进行替换 base_dir=base_dir.replace('\\','/') #获取项目文件的根目录路径 base=base_dir.split('/Website')[0] #指定截图存放路径 filepath=base+'/Website/test_report/screenshot/'+filename print(filepath) #截图 driver.get_screenshot_as_file(filepath) #发送邮件函数 def send_mail(latest_report,subject): #账号信息等 smtpserver = "smtp.163.com" user = "******@163.com" #邮件账号 password = "******" #输入邮件服务的密码 sender = "******@163.com" #发送邮件的账号 receives = ['******@qq.com', ''] #收件人,这里可以是多个收件测试人员 subject = subject mail_content='详细请看附件' #邮件的标题 # 构造附件内容 file_path = latest_report send_file = open(file_path, 'rb').read() name = os.path.basename(file_path) att = MIMEText(send_file, 'base64', 'utf-8') att['Content-Type'] = 'application/octet-stream' att.add_header('Content-Disposition', 'attachment', filename=('gbk', '', name)) # 可以实现中文附件名称 # 构造发送与接收信息 msg = MIMEMultipart() msg.attach(MIMEText(mail_content, 'html', 'utf-8')) msg['subject'] = Header(subject, 'utf-8') msg['From'] = sender msg['To'] = ','.join(receives) msg.attach(att) #发送邮件 smtp=smtplib.SMTP_SSL(smtpserver,465) smtp.helo(smtpserver) smtp.ehlo(smtpserver) smtp.login(user,password) print('开始发送邮件!') smtp.sendmail(sender,receives,msg.as_string()) smtp.quit() print('发送邮件结束!') #报告函数 def latest_report(report_dir): lists=os.listdir(report_dir) lists.sort(key=lambda fn:os.path.getatime(report_dir+'\\'+fn)) print('最新的报告是:'+lists[-1]) file=os.path.join(report_dir,lists[-1]) return file
#如果你发送邮件只需要标题跟正文做预警提醒,则只需要: def send_mail(res_mail,sender_mail,content,subject='【预警邮件】请重点关注该邮件阐述可能正在发生的缺陷!'): """ 发送邮件不带附件,只有标题跟主题 :param res_mail: 接收方邮件 type:str :param sender_mail: 发送方邮件账号密码 type:dict :param content: 邮件正文信息 type:str :param subject: 邮件主题,可选 type:str :return: none """ #第三方STMP服务 mailhost = "smtpav.travelsky.com" #第三方host mailuser = sender_mail['user'] #邮件账号 mailpassword = sender_mail['password'] #输入邮件服务的密码 sender = sender_mail['user'] #发送邮件的账号 receives = res_mail #收件人,这里可以是多个收件测试人员 subject = subject mail_content = MIMEText(content, 'plain', 'utf-8') #邮件的正文内容 mail_content['subject'] = Header(subject, 'utf-8') #邮件的标题 mail_content['From'] = sender mail_content['To'] = ','.join(receives) # 发送邮件 smtp = smtplib.SMTP_SSL(mailhost, 465) smtp.helo(mailhost) smtp.ehlo(mailhost) smtp.login(mailuser, mailpassword) try: print('开始发送邮件!') smtp.sendmail(sender, receives, mail_content.as_string()) smtp.quit() print('发送邮件结束!') except smtplib.SMTPException: print('无法发送邮件')