前段时间弄一个测试框架,满足公司简单网站的测试,整合了一个函数模块,包括常用的截图、邮件发送、测试报告生成,具体代码如下
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