#!/usr/bin/python
# coding: utf-8
'''
执行测试用例并将结果返回至邮箱
'''
import sys
import time, os, unittest
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr

import HTMLTestRunner
import datetime
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import logging
#from Test.Common.AppiumBase import install_app
d = datetime.datetime.now()
path = "\\".join(sys.path[0].split("\\")[:5])

test_dir = path+r'\Testcase'
filepath=path+r"\Report"
PATH = lambda p: os.path.abspath(os.path.join(os.path.dirname(__file__), p))
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(filename='my.log', level=logging.DEBUG, format=LOG_FORMAT)

def createSuite(test_dir):
    testunit = unittest.TestSuite()
    discover = unittest.defaultTestLoader.discover(test_dir,pattern='Test_*.py')

    for suite in discover:
        for case in suite:
            testunit.addTest(case)
    return testunit

def runTestCase(testunit):
    report_path = filepath+"\RESULT_%s.html"%d.strftime('%Y-%m-%d-%H-%M-%S')
    fp=open(report_path,'wb')
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title=u"测试报告",description=u"描述")
    suite = createSuite(test_dir)
    runner.run(suite)
    fp.close()
    return fp,report_path


def send_report_to_email(result):
    # SMTP服务器和相关的配置信息
    smtp_server = 'smtp.126.com'
    from_addr = 'jiang_sisi@126.com'
    to_addr = 'jiang_sisi@126.com'
    password = 'ALAPCHBZXHYINAKD'
    title = '测试结果'
    mail_body = result
    with open(result,"rb") as f:
        mail_body = f.read()
    # 1.创建邮箱（邮件内容，发送人，收件人和标题等）
    msg = MIMEMultipart()
    msg['From'] = formataddr(('jiangsisi', from_addr))
    msg['To'] = formataddr(('jiangsisi', to_addr))
    msg['Subject'] = title
    # 2.正文
    att = MIMEText(mail_body, 'html', 'utf-8')  # 发送html文件内容
    msg.attach(att)
    # 3.附件内容
    att = MIMEText(mail_body, 'html', "utf-8")  # 发送附件
    att['Content-type'] = 'application/octet-stream'
    att['Content-Disposition'] = 'attachment; filename="test_report.html"' #附件名称
    msg.attach(att)
    # 2.登录账号
    server = smtplib.SMTP_SSL(smtp_server, 465)
    server.login(from_addr, password)
    try:
        server.sendmail(from_addr, to_addr, msg.as_string())
        server.quit()
        return ("邮件发送成功.")
    except Exception as e:
        return ('邮件发送失败,错误代码为: %s' % e)



if __name__ == "__main__":
    try:
        testunit = createSuite(test_dir)
        result,path = runTestCase(testunit)
        s = send_report_to_email(path)
        print(s)


    except Exception as e:
        print(e)
        logging.debug(msg="ERROR:%s"%e)