# coding=utf-8
import unittest
import time
import HTMLTestRunner_jpg
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from unittestreport import TestRunner
import os
import sys
import json
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
#
#
# '''
# #### 下面三行代码python2报告出现乱码时候可以加上####
# import sys
# reload(sys)
# sys.setdefaultencoding('utf8')
# '''
#
# # 优化版执行所有用例并发送报告，分四个步骤
# # 第一步加载用例
# # 第二步执行用例
# # 第三步获取最新测试报告
# # 第四步发送邮箱 （这一步不想执行的话，可以注释掉最后面那个函数就行）
#
#
# # 当前脚本所在文件真实路径
# cur_path = os.path.dirname(os.path.realpath(__file__))
#
#
# #第一步具体方法
# def add_case(caseName="case", rule="case*.py"):
#     '''第一步：加载所有的测试用例'''
#     case_path = os.path.join(cur_path, caseName)  # 用例文件夹
#     # 如果不存在这个case文件夹，就自动创建一个
#     if not os.path.exists(case_path):os.mkdir(case_path)
#     print("title case path:%s"%case_path)
#     # 定义discover方法的参数
#     discover = unittest.defaultTestLoader.discover(case_path,
#                                                   pattern=rule,
#                                                   top_level_dir=None)
#     print(discover)
#     return discover
#
# #第二步具体方法
# def run_case(all_case, reportName="report"):
#
#     '''第二步：执行所有的用例, 并把结果写入HTML测试报告'''
#     now = time.strftime("%Y_%m_%d_%H_%M_%S")
#     report_path = os.path.join(cur_path, reportName)  # 用例文件夹
#     # 如果不存在这个report文件夹，就自动创建一个
#     if not os.path.exists(report_path):os.mkdir(report_path)
#     #{}和。format（）去掉 就是替换这个文件。
#  #  report_abspath = os.path.join(report_path, "result{}.html".format(now))
#     report_abspath = os.path.join(report_path, "result.html")
#     print("report path:%s"%report_abspath)
#     fp = open(report_abspath, "wb")
#
#     #星宇的一套页面效果
#     runner = HTMLTestRunner_jpg.HTMLTestRunner(stream=fp,
#                                            title=u'更美-ai自动化测试报告,测试结果如下：',
#                                            description=u'用例执行情况：')
#     #调用add_case函数返回值   获取最终结果值
#     res = runner.run(all_case)
#     # 获取他的错误的用例数量。
#     error_count = res.error_count
#     #获取他的失败的用例数量。
#     failure_count = res.failure_count
#     fp.close()
#     return error_count,failure_count
#
#
#     #奉龙的这一套 报告页面效果
#     from BeautifulReport import BeautifulReport
#
#     runner = BeautifulReport(all_case)
#     runner.report('更美ai-接口自动化',filename='更美ai.html',log_path='report')
#     #
#     # return runner.error_count,runner.failure_count
#
# #第三步具体方法
# def get_report_file(report_path):
#     '''第三步：获取最新的测试报告'''
#     lists = os.listdir(report_path)
#     lists.sort(key=lambda fn: os.path.getmtime(os.path.join(report_path, fn)))
#     print (u'最新测试生成的报告： '+lists[-1])
#     # 找到最新生成的报告文件
#     report_file = os.path.join(report_path, lists[-1])
#     return report_file
#
# #第四步具体方法
def send_mail(sender, psw, receiver, smtpserver, report_file, port):
    '''第四步：发送最新的测试报告内容'''
    with open(report_file, "rb") as f:
        mail_body = f.read()
    # 定义邮件内容
    now_time = time.strftime("%Y-%m-%d %H:%M:%S")
    msg = MIMEMultipart()
    body = MIMEText(mail_body, _subtype='html', _charset='utf-8')
    #添加报告title时间戳
    msg['Subject'] = u"更美-ai_接口自动化测试报告"
    #msg['Subject'] = u"自动化测试报告_%s"%now_time
    msg["from"] = sender
    msg["to"] = "".join(receiver)     # 只能字符串
    msg.attach(body)
    # 添加附件
    att = MIMEText(open(report_file, "rb").read(), "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = 'attachment; filename= "report.html"'
    msg.attach(att)
    try:
        smtp = smtplib.SMTP()
        smtp.connect(smtpserver)                      # 连服务器
        smtp.login(sender, psw)
    except:
        smtp = smtplib.SMTP_SSL(smtpserver, port)
        smtp.login(sender, psw)                       # 登录
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
    print('title report email has send out !')
#
#
#
#
# # 整体调用流程
# if __name__ == "__main__":
#     # 1 加载用例
#     all_case = add_case()
#
#     # 2 执行用例
#     error_count,failure_count = run_case(all_case)
#
#     # 获取最新的测试报告文件
#     report_path = os.path.join(cur_path, "report")  # 用例文件夹
#
#     # 3获取最新的测试报告
#     report_file = get_report_file(report_path)
#
# # -----------------------------------------------以下为第四步的配置传参内容-----------------------------------------------
#     # 邮箱配置  发送邮箱的地址
#     sender = "liubingyin@igengmei.com"     # sender = "l709188456@163.com"
#     #邮箱密码
#     psw = "cgBP3fw2ZNgp3L5r"    #psw = "3328378"
#     # 163服务器的servers
#     #smtp_server = "smtp.163.com"
#     # 公司地址的服务器server
#     smtp_server = "smtp.exmail.qq.com"
#     port = 465
#     # 发给谁的邮箱
#     receiver = ["liubingyin@igengmei.com"]
# # --------------------------------------------------------------------------------------------------------------------
#     # 4最后一步发送报告
#     send_mail(sender, psw, receiver, smtp_server, report_file, port)



if __name__ == '__main__':

    # case_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),"case")
    case_path = os.path.join(os.path.realpath(""), "case")

    discover = unittest.defaultTestLoader.discover(case_path,pattern="case*.py",top_level_dir=None)

    # from BeautifulReport import BeautifulReport
    #
    # # 放入对应的html文件是在这里放 （report_dir='report'）
    # runner = BeautifulReport(discover)
    # runner.report('更美android-埋点自动化',filename='更美android埋点.html',report_dir='report')
    # error = runner.error_count
    # failure = runner.failure_count
    runner = TestRunner(discover, report_dir="report")
    res = runner.rerun_run(count=3)
    # 参数 说明 失败重跑的次数
    # res = runner.rerun_run(count=3)
    report_path = os.path.join(os.path.realpath(""), "report")
    # 这是为了获取report里面文件列表
    lists = os.listdir(report_path)
    lists.sort(key=lambda fn: os.path.getmtime(os.path.join(report_path, fn)))
    print (u'最新测试生成的报告： '+lists[-1])
    # 找到最新生成的报告文件
    report_file = os.path.join(report_path, lists[-1])

    sender = "liubingyin@igengmei.com"     # sender = "l709188456@163.com"
    #邮箱密码
    psw = "cgBP3fw2ZNgp3L5r"    #psw = "3328378"
    # 163服务器的servers
    #smtp_server = "smtp.163.com"
    # 公司地址的服务器server
    smtp_server = "smtp.exmail.qq.com"
    port = 465
    # 发给谁的邮箱
    receiver = ["liubingyin@igengmei.com"]
    # --------------------------------------------------------------------------------------------------------------------
    # 4最后一步发送报告
    send_mail(sender, psw, receiver, smtp_server, report_file, port)









    # discover = unittest.defaultTestLoader.discover("case", pattern="case*.py", top_level_dir=None)
    # runner = TestRunner(discover, report_dir="report")
    # res = runner.rerun_run(count=3)
    # report_path = os.path.join(os.path.realpath(""), "report")
    # lists = os.listdir(report_path)
    # lists.sort(key=lambda fn: os.path.getmtime(os.path.join(report_path, fn)))
    # print(u'最新测试生成的报告： ' + lists[-1])
    # # 找到最新生成的报告文件
    # report_file = os.path.join(report_path, lists[-1])
    # sender = "liubingyin@igengmei.com"  # sender = "l709188456@163.com"
    # # 邮箱密码
    # psw = "cgBP3fw2ZNgp3L5r"  # psw = "3328378"
    # # 163服务器的servers
    # # smtp_server = "smtp.163.com"
    # # 公司地址的服务器server
    # smtp_server = "smtp.exmail.qq.com"
    # port = 465
    # # 发给谁的邮箱
    # receiver = ["liubingyin@igengmei.com"]
    # # --------------------------------------------------------------------------------------------------------------------
    # # 4最后一步发送报告
    # send_mail(sender, psw, receiver, smtp_server, report_file, port)