main.py 2.62 KB
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os,time
import sys
import unittest
import re
import HTMLTestRunner_cn
import commons.ConfigDB as db
from discover import DiscoveringTestLoader
from commons import SendEmail as em
from commons import common as com
from commons.MySession import my
from commons.scripts import delReport



def Create_Testcase_suite(path=""):
    '''创建测试套件'''
    if path != "":
        path += "/"
    print(path)
    testunit = unittest.TestSuite()
    test_Loader = DiscoveringTestLoader()
    discover = test_Loader.discover("./testcase/{}".format(path), pattern='test_*.py', top_level_dir=None)
    # print(discover)
    for test_suite in discover:
        testunit.addTests(test_suite)
    #     print(testunit)
    return testunit


def Run_Testcase(testsuit, head=""):
    '''运行测试用例并生成报告'''
    if (head in my.market.keys()):
        head = "[" + my.market[head] + "]"
    now = time.strftime("%Y-%m-%d %H_%M_%S", time.localtime())
    path = os.path.dirname(os.path.abspath(sys.argv[0]))
    report_file = path + "/report/" + now + "_result.html"
    # 创建报告文件
    fp = open(report_file, 'wb')

    runner = HTMLTestRunner_cn.HTMLTestRunner(
        stream=fp,
        title=u'进门收费{}--接口测试报告'.format(head),
        description=u'用例简要执行情况如下:(注:报告详细信息需要下载report.html并用浏览器打开)',
        verbosity=2)
    # 执行用例
    runner.run(testsuit)
    # 关闭文件
    fp.close()
    delReport.delReport(path)
    return report_file


def Send_email(filename):
    '''判断邮件发送逻辑'''
    l = eval(com.get_global_config("global_data", "email", "to_list").lower())
    c = eval(com.get_global_config("global_data", "email", "cc_list").lower())
    if type(l) != type([]):
        raise Exception("error,pls input list type send-email address")
    elif len(l) == 0:
        print("\n To_list of send-email is null,won't send email!")
    elif len(l) != 0:
        for i in l:
            print("\n check send-email format : {}".format(i))
            if re.match(r'^[0-9a-zA-Z_]{1,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$', i):
                pass
            else:
                raise Exception("error,pls check your send-email format")
        # 发送邮件
        em.send_email(filename, send_to=l, cc_to=c)
    else:
        print("\n Haven't sent the email,pls check send-email address!")


if __name__ == "__main__":
    # 检测数据库
    db.mysql_conn_test()
    # 创建测试套,运行测试用例,生成报告
    report = Run_Testcase(Create_Testcase_suite())
    # 发送邮件
    Send_email(report)