python - 读取xml文档生成HTML文档-测试报告

report_xue.xml



    
        
            
        
    
    
        
            
        
    

template_local



    
    
    xml文件生成html报告
    
    
    
    
    
    


HTML报告
报告汇总
详细数据
编号 domain query title 运行时长 结果 操作

reportutils.py

# coding=utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf-8')
import os
import time
import json
import platform
from distutils.sysconfig import get_python_lib


__all__ = ['BeautifulReport']




HTML_IMG_TEMPLATE = """
    
    
    
    

""" class OutputRedirector(object): """ Wrapper to redirect stdout or stderr """ def __init__(self, fp): self.fp = fp def write(self, s): self.fp.write(s) def writelines(self, lines): self.fp.writelines(lines) def flush(self): self.fp.flush() stdout_redirector = OutputRedirector(sys.stdout) stderr_redirector = OutputRedirector(sys.stderr) SYSSTR = platform.system() SITE_PAKAGE_PATH = get_python_lib() print(SITE_PAKAGE_PATH) FIELDS = { "testPass": 0, "testResult": [ ], "testName": "", "testAll": 0, "testFail": 0, "beginTime": "", "totalTime": "", "testSkip": 0 } class MakeResultJson: """ make html table tags """ def __init__(self, datas): # tuple """ init self object :param datas: 拿到所有返回数据结构 """ self.datas = datas self.result_schema = {} def __setitem__(self, key, value): """ :param key: self[key] :param value: value :return: """ self[key] = value def __repr__(self): # str """ 返回对象的html结构体 :rtype: dict :return: self的repr对象, 返回一个构造完成的tr表单 """ keys = ( 'domain', 'queryContent', 'title', 'spendTime', 'status', 'log', ) for key, data in zip(keys, self.datas): self.result_schema.setdefault(key, data) return json.dumps(self.result_schema) def stopTest(result_list,topic_type,queryContent,group_match_id,status,error_msg,request_time,db_time): """ 当测试用力执行完成后进行调用 :return: """ result_list.append(tuple([topic_type,queryContent,group_match_id, str(float(request_time)+float(db_time))[0:5], status, error_msg])) return result_list def stopTestRun(title,result_list,pass_count,failure_count,skipped_count,error_count): """ 所有测试执行完成后, 执行该方法 :param title: :return: """ FIELDS['testPass'] = pass_count FIELDS['testResult'] = [] # 注释掉这一句,最后生成的报告包含所有记录 for item in result_list: item = json.loads(str(MakeResultJson(item))) FIELDS.get('testResult').append(item) FIELDS['testAll'] = len(result_list) FIELDS['testName'] = title FIELDS['testFail'] = failure_count FIELDS['testError'] = error_count FIELDS['testSkip'] = skipped_count return FIELDS class BeautifulReport(): def __init__(self): self.title = 'Diff测试报告' self.filename = 'report.html' self.FIELDS = None def set_fields(self,fileds,begine_time,total_time,versioninfo, api_info): self.FIELDS = fileds FIELDS['beginTime'] = begine_time try: time_set = str(total_time).split(':') FIELDS['totalTime'] = str(int(time_set[0])*3600+int(time_set[1])*60+int(time_set[2]))+"s" except Exception: FIELDS['totalTime'] = str(total_time)+"s" FIELDS['testVersion'] = versioninfo FIELDS['testAPI'] = api_info def report(self, description, filename, log_path='.', temp_name='template_local'): """ 生成测试报告,并放在当前运行路径下 :param log_path: 生成report的文件存储路径 :param filename: 生成文件的filename :param description: 生成文件的注释 :return: """ if filename: self.filename = filename if filename.endswith('.html') else filename + '.html' if description: self.title = description self.log_path = os.path.dirname(__file__) print '*'*50, self.log_path self.output_report(temp_name=temp_name) # 运行一个suit重写一次 def output_report(self, temp_name='template_local'): """ 生成测试报告到指定路径下 :return: """ template_path = self.log_path + '/' + temp_name override_path = self.log_path + '/' with open(template_path, 'rb') as file: body = file.readlines() file.close() with open(override_path + self.filename, 'wb') as write_file: for item in body: if item.strip().startswith(b'var resultData'): head = ' var resultData = ' item = item.decode().split(head) item[1] = head + json.dumps(self.FIELDS, ensure_ascii=False, indent=4) item = ''.join(item).encode() item = bytes(item) + b';\n' write_file.write(item) write_file.close()

xml_to_html_test_xue.py

# coding=utf-8
import json
from xml.etree import ElementTree as et
import time
from reportutils import BeautifulReport, stopTest, stopTestRun
import sys
reload(sys)
sys.setdefaultencoding('utf-8')


def str_replace(input_str, old_char, new_char):
    input_str = input_str.replace(old_char, new_char)
    while (input_str.find(old_char)) > -1:
        input_str = input_str.replace(old_char, new_char)
    return input_str


def xml2html(xml_file=None):
    json_data = []
    total_time = 0.0
    error_count = 0
    pass_count = 0
    fail_count = 0
    skipped_count = 0
    root = et.parse(xml_file)
    for each in root.getiterator("testcase"):
        print '------ each = ', each

        tempDict = each.attrib
        print '------ tempDict = ', tempDict
        print '------ each.tag = ', each.tag

        print '>>>>>> each.getchildren() = ', each.getchildren()
        for childNode in each.getchildren():
            print '------ childNode.text = ', childNode.text
            tempDict[childNode.tag] = childNode.text

        # tempJson = json.dumps(tempDict, ensure_ascii=False)

        if tempDict["name"].__eq__("runTest"):
            continue
        else:
            query_info_set = tempDict["name"].split('+')

            queryContent = query_info_set[1]
            domain = query_info_set[2]
            title = query_info_set[0].replace("-", ".")
            spendTime = tempDict["time"]

            total_time += float(tempDict["time"])

            try:
                log = json.dumps(
                    tempDict["failure"],
                    ensure_ascii=False,
                    indent=4)
                status = "fail"
                fail_count += 1
            except Exception:
                try:
                    log = json.dumps(
                        tempDict["error"], ensure_ascii=False, indent=4)
                    status = "error"
                    error_count += 1
                except Exception:
                    try:
                        log = json.dumps(
                            tempDict["skipped"], ensure_ascii=False, indent=4)
                        status = "skipped"
                        skipped_count += 1
                    except Exception:
                        status = "pass"
                        log = "pass"
                        pass_count += 1
        stopTest(json_data, domain, queryContent, title, status, log, spendTime, 0)

    end_result = dict()
    end_result["result_list"] = json_data
    end_result["fail"] = fail_count
    end_result["pass"] = pass_count
    end_result["error"] = error_count
    end_result["skipped"] = skipped_count
    end_result["total_time"] = float(1)
    end_result["begin_time"] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

    result = BeautifulReport()
    api_info = "清国-中华民国-中华人民共和国"
    version_info = "v1.0"

    title = "xml_to_html"
    res = stopTestRun(title, end_result["result_list"], end_result["pass"], end_result["fail"], end_result["skipped"], end_result["error"])
    result.set_fields(res, end_result["begin_time"], end_result["total_time"], version_info, api_info)
    # 报告生成
    result.report(filename='report_xue.html', description='test', log_path='', temp_name='template_local')


if __name__ == "__main__":
    xml_file = "report_xue.xml"
    xml2html(xml_file=xml_file)

 

你可能感兴趣的:(python)