# -*- coding: utf-8 -*-
# 报告生成报告类
# 作者: 陈磊
# 时间: 2019-10-21

import HTMLTestRunner
import unittest
import time
import sys
import os

from datetime import datetime
from WorkBase import WorkBase
from WorkUtils.UtilsLogOld import UtilsLogOld


class UtilsReport:
    def __init__(self, case_info, description, version):
        """
        :param case_info: 用例信息
        :param description: 用例描述
        :param version: 版本号
        """
        self.log = UtilsLogOld()
        self.log_path = self.log.path
        self.log_name = self.log.logger_name
        # 注释掉通过拼接方式生成路径
        # self.case_path = WorkBase().case_path + case_path
        self.case_info = case_info
        self.case_path = case_info[0]
        self.case_name = case_info[-1][0:-3]
        self.report_path = ""
        self.report_name = ""
        self.description = description
        self.create_time = datetime.today().strftime("%Y%m%d%H%M%S")
        self.result = []
        self.version = version

    def run(self):
        """
        运行方法
        :return:
        """
        self.log.debug("开始执行自动化测试用例......")
        test_case = unittest.TestSuite()
        self.log.debug("加载测试用例......")
        sys.path.append(self.case_path)
        case = __import__(self.case_name)
        test_suite = [case.case_suite()]
        for i in range(len(test_suite)):
            test_case.addTests(test_suite[i])
        self.log.debug("加载完成")

        # 生成测试报告文件
        # 更新获取的版本号生成文件
        self.report_path = WorkBase().report_path + self.version + "\\" + self.case_name + "\\"
        if os.path.exists(self.report_path):
            pass
        else:
            os.makedirs(self.report_path)

        self.report_name = self.description[0:6] + "_" + self.create_time + ".html"
        report = self.report_path + self.report_name
        # 打开文件
        fp = open(report, "wb")
        # 执行测试报告
        runner = HTMLTestRunner.HTMLTestRunner(
            stream=fp,
            title="嫲嫲团接口自动化测试报告",
            description="当前版本号:"+str(self.version)+",测试模块:"+self.description,
            verbosity=2
        )
        self.log.debug("自动化任务执行开始")
        result = runner.run(test_case)
        self.log.debug("保存文件...")
        self.log.debug("测试报告文件路径:")
        self.log.debug(self.report_path)
        self.log.debug("测试报告文件名称:")
        self.log.debug(self.report_name)
        self.log.debug("日志文件路径:")
        self.log.debug(self.log_path)
        self.log.debug("日志文件名称:")
        self.log.debug(self.log_name)

        # 保存文件
        self.log.debug("自动化任务执行结束")
        self.result = result.result
        fp.close()
        self.print_result()

    def print_result(self):
        """
        输出测试结果方法
        :return:
        """
        time.sleep(2)
        success = 0
        failures = 0
        failures_list = []
        errors = 0
        errors_list = []
        total = len(self.result)
        for x, y in enumerate(self.result):
            if y[0] == 0:
                success += 1
            elif y[0] == 1:
                failures += 1
                failures_list.append(y[1])
            elif y[0] == 2:
                errors += 1
                errors_list.append(y[1])
        print("----------------------------------------------------------------")
        # print("当前版本号:", self.version)
        print("自动化任务结果预览:")
        print("执行用例个数:", total)
        print("成功:", success)
        print("失败:", failures)
        print("失败用例:", failures_list)
        print("错误:", errors)
        print("错误用例:", errors_list)
        print("----------------------------------------------------------------")

    def cmd_run(self):
        """
        CMD下运行方法
        :return:
        """
        if self.description == "" or self.version == "":
            self.log.error("运行参数解析失败,请重新输入参数!")
            self.log.error("可以输入 -h,获取帮助信息!")
        else:
            self.run()
