收集case
def get_total_cases(filename):
"""
解析用例配置文件
:param filename: 用例集配置文件路径
:return: 返回suite测试用例集
"""
with open(filename, 'r', encoding='utf-8') as f:
content = " ".join([r.rstrip() for r in f])
html_code = etree.HTML(content, etree.HTMLParser())
org_str = "//div[@class='testcase']/div"
path_list = html_code.xpath(org_str)
case_lists = {}
for index in range(1, len(path_list) + 1):
search_str = org_str + f"{[index]}/file"
file_list = html_code.xpath(search_str)
for child_index in range(1, len(file_list) + 1):
case_path = 'testcase.' + path_list[index - 1].attrib['class'] + "." + file_list[child_index - 1].attrib[
'class']
child_search_str = search_str + f"{[child_index]}/test_case/@name"
case_list = html_code.xpath(child_search_str)
case_lists[case_path] = case_list
return case_lists
添加case到suites中
def add_case_to_suites(case_dic: dict):
"""
添加测试用到unittest suite
:param case_dic: 用来集的字典
:return:
"""
suites = unittest.TestSuite()
for key, value in case_dic.items():
if value:
path = ".".join(key.split('.')[:-1])
class_demo = key.split('.')[-1]
params = import_module(path)
getattr_result = getattr(params, class_demo)
for test_case in value:
suites.addTest(getattr_result(test_case))
return suites
执行case
case_lists = get_total_cases(case_path)
suite = add_case_to_suites(case_lists)
runner = TestRunner(suite, filename="test_config", templates=2)
runner.run()