收集测试用例:
1、初始化testloader: testloader = unittest.TestLoaser()
2、执行文件夹下所有的测试用例,suite = testloader.discover(case_path)
3、将测试报告写入文件夹中:
with open(file=file_path,mode='w',encoding='utf-8') as f:
runner = unittest.TextTestRunner(f,verbosity=2)
runner.run(suite)
import os.path
import unittest
from datetime import datetime
testloader = unittest.TestLoader() # 初始化
dir_path = os.path.dirname(os.path.abspath(__file__)) # 获取项目路径
case_path = os.path.join(dir_path, 'test_case') # 获取用例路径
suite = testloader.discover(case_path) # 加载用例路径下的所有用例
report_path = os.path.join(dir_path, 'report') # 创建report报告的路径
if not os.path.exists(report_path):
os.mkdir(report_path)
now_time = datetime.now().strftime('%Y%m%d-%H%M%S') # 获取当前时间
file_name = 'test_report_{}.txt'.format(now_time) # 根据当前时间拼接为报告名称
file_path = os.path.join(report_path, file_name) # 保存报告的路径
with open(file=file_path, mode='w', encoding='utf-8') as f: # 将报告写入到文件
runner = unittest.TextTestRunner(stream=f, verbosity=2)
runner.run(suite)
参数:
#case_path 用例的路径
#file_path 保存报告的路径
收集用例的方式还有很多种,例如:
加载某一个模块:testloder.loadTestsFromModule(模块名)