python中的unittest
Unittest是python里面的单元测试框架,方便组建测试用例,执行用例,并生成测试报告
1、unittest规则
- 测试类,继承单元测试unittest.TestCase这个类
- 测试方法(用例)必须以test开头
- 测试类就是多个用例的一个集合,相当于是测试用例的一个模块
- 断言:self.assertEqual(测试结果, 期望结果)
2、unittest执行顺序
- 前置条件:setUp(self),一般处理一些前置操作,比如每个请求都要用到的头文件header,登陆的token,域名设置等
- 后置条件:tearDown(self),后置条件一般是做数据清理的操作
- 前置与后置是非必须的,可有可无
- test开头的测试方法
- setUpClass(cls)只执行一次前置,上面必须加@classmethod
- tearDownClass(cls)只执行一次,在所有的用例执行后最后执行,上面必须加@classmethod
- 执行顺序:先setUp(self)--1,再test开头的测试方法--2,最后执行tearDown(self)--3,执行测试方法时的顺序是按照(assic码):0-9 ,A-Z, a-z顺序执行的。如果有setUpClass(cls)--4/tearDownClass(cls)--5,那么最后的执行顺序是4-->1-->2-->3-->5,而且要注意的是1和3是在每执行一条用例的时候都会执行的,而4/5不管有多少条用例,只会执行一次。
3、批量执行测试用例(discover)
- 首先定义要执行用例的目录
- 然后用unittest中的discover方法拿到要执行的文件
- 再用unittest中的run去执行上一步获取到的要执行的文件
# coding:utf-8 import os import unittest def all_case(): """加载指定目录下的所有的用例""" case_dir = os.getcwd() discover = unittest.defaultTestLoader.discover(case_dir, pattern="*_test.py") #print(discover) print(case_dir) return discover if __name__ == "__main__": runner = unittest.TextTestRunner() runner.run(all_case())
4、生成报告(HTMLTestRunner)
- 首先定义报告的路径
- 第二步是创建和打开文件
- 第三步是用HTMLTestRunner来生成报告
- 第四步是执行所有的用例
- 最后一步记得关闭打开的文件
def run_case(all_case, reportName="report"): """执行所有的用例,并把结果写入HTML测试报告""" report_path = os.path.join(cur_path, reportName) # 如果不存在report这个文件,就自动创建一个 if not os.path.exists(report_path): os.mkdir(report_path) report_path1 = os.getcwd() + "\\report\\" + "result_" + time.strftime("%Y%m%d_%H%M%S") + ".html" print(report_path1) report_name = "result_" + time.strftime("%Y%m%d_%H%M%S") + ".html" report_abspath = os.path.join(report_path, report_name) open_report = open(report_abspath, "wb+") runner = HTMLTestRunner.HTMLTestRunner(stream=open_report, title=u'接口自动化测试报告', description=u'用例执行报告') runner.run(all_case) open_report.close()
5、将测试报告通过邮件发送
- 首先得要打开需要发送的测试报告,读取报告内容
- 定义邮件要发送的内容:设置邮件标题、发送人和接收人、测试报告附件
- 链接邮箱进行登录
- 发送邮箱
def send_mail(sender, psw, receiver, SMTP_server, report_file, port): """发送最新的测试报告到指定邮箱""" open_file = open(report_file, "rb") with open_file 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"] = ",".join(receiver) msg.attach(body) # 添加附件 att = MIMEText(open(report_file, "rb").read(), "base64", "utf-8") att['Content-Type'] = "application/octet-stream" att['Content-Disposition'] = 'attachment; filename=report_name' msg.attach(att) try: smtp = smtplib.SMTP() smtp.connect(SMTP_server) smtp.login(sender, psw) except: smtp = smtplib.SMTP_SSL(SMTP_server, port) smtp.login(sender, psw) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() print("发送成功")
学而不思则罔,思而不学则殆