工程结构如下:
test1.py
1 import unittest 2 3 4 class Test(unittest.TestCase): 5 '''我的第一个测试类''' 6 7 @classmethod 8 def setUp(self): 9 pass 10 11 def test_case_1(self): 12 '''测试2是否等于2''' 13 self.assertEqual(2, 2, '不相等2!=2') 14 15 def test_case_2(self): 16 '''测试2是否等于3''' 17 self.assertEqual(2, 3, '不相等2!=3') 18 19 @classmethod 20 def tearDown(self): 21 pass 22 23 24 if __name__ == '__main__': 25 unittest.main()
test2.py
1 import unittest 2 3 4 class Test(unittest.TestCase): 5 '''我的第二个测试类''' 6 7 @classmethod 8 def setUp(self): 9 pass 10 11 def test_case_3(self): 12 '''测试20是否等于20''' 13 self.assertEqual(20, 20, '不相等20!=20') 14 15 def test_case_4(self): 16 '''测试2是否等于3''' 17 self.assertEqual(20, 30, '不相等20!=30') 18 19 @classmethod 20 def tearDown(self): 21 pass 22 23 24 if __name__ == '__main__': 25 unittest.main()
runtest.py
1 from HTMLTestRunner import HTMLTestRunner 2 import unittest 3 import time 4 import smtplib 5 from email.mime.text import MIMEText 6 from email.mime.multipart import MIMEMultipart 7 import os 8 9 10 # 发送邮件 11 def send_test_report(file_name): 12 # 发送邮箱的服务器、账号、密码 13 server = 'smtp.qq.com' 14 user = '847486345' 15 passwd = 'jcccxafqagggbcaf' 16 17 # 发送邮箱、接收邮箱 18 sender = '847486345@qq.com' 19 receiver = '18109230755@163.com,xhj0755@dingtalk.com' 20 21 # 邮件的标题、内容 22 subject = '自动化测试报告demo' + time.strftime('%Y-%m-%d %H_%M_%S') 23 fp = open(file_name, 'rb') 24 file_content = fp.read() 25 fp.close() 26 27 # 构造邮件(主题、正文+附加) 28 msgRoot = MIMEMultipart('related') 29 msgRoot['Subject'] = subject 30 31 body = MIMEText(file_content, 'html', 'utf-8') 32 att = MIMEText(file_content, 'base64', 'utf-8') 33 att['Content-Type'] = 'application/octet-stream' 34 att['Content-Disposition'] = 'attachment; filename=test_report.html' 35 36 msgRoot.attach(att) 37 msgRoot.attach(body) 38 39 # 连接邮箱、发送邮件 40 smtp = smtplib.SMTP() 41 smtp.connect(server) 42 smtp.login(user, passwd) 43 smtp.sendmail(sender, receiver.split(','), msgRoot.as_string()) 44 smtp.quit() 45 46 47 # 查找最新报告 48 def new_report(report_dir): 49 lists = os.listdir(report_dir) 50 lists.sort(key=lambda fn:os.path.getmtime(report_dir + '\' + fn)) 51 file_new = os.path.join(report_dir, lists[-1]) 52 return file_new 53 54 55 if __name__ == '__main__': 56 test_dir = './' 57 report_dir = './report/' 58 discover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py') # 找到需要执行的测试用例 59 60 now_time = time.strftime('%Y-%m-%d %H_%M_%S') 61 file_name = report_dir + 'test_result' + now_time + '.html' 62 fp = open(file_name, 'wb') 63 runner = HTMLTestRunner(stream=fp, 64 title='测试报告demo', 65 description='详细测试结果如下') 66 67 runner.run(discover) # 执行测试用例,并生成测试报告 68 print('生成的测试报告为' + file_name) 69 fp.close() 70 71 file_name = new_report(report_dir) # 找到最新的测试报告 72 print('最新报告为' + file_name) 73 send_test_report(file_name) # 将最新的测试报告以邮件的形式发送
测试报告如下: