加载指定用例并发送报告


import  os
from mode.get_token import Token
from report.HTMLTestRunner import HTMLTestRunner
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from log.mylog import logger,Logger
import unittest
import datetime

current_path = os.path.dirname(__file__)
# pro_path是工程目录,构造了一个case_pth路径
case_path = os.path.join(current_path + '/' + "testCase")

case_list = []
# 不执行的文件用例
not_case_list = [
    'test01.py',     # 


]


def modify_text(report_path):
    case_result = report_path  + "/result/" + 'case_result.txt'
    f= open(case_result, "a+")
    f.seek(0)
    print('清空文件')
    print(case_result)
    f.truncate()   #清空文件
    f.close()



def send_email_by_qq(to,files,host):
    sender_mail = 'test@qq.com'
    sender_pass = 'test@qq.com'

    # 设置总的邮件体对象,对象类型为mixed
    msg_root = MIMEMultipart('mixed')
    # 邮件添加的头尾信息等
    msg_root['To'] = ";".join(to)
    # 邮件的主题,显示在接收邮件的预览页面
    subject = '%s 自动化测试结果'%(host)
    msg_root['subject'] = Header(subject, 'utf-8')

    # 构造文本内容
    text_info = '您好!\n  请查看附件内容'
    text_sub = MIMEText(text_info, 'plain', 'utf-8')
    msg_root.attach(text_sub)


    for file in files:
        txt_file = open(file, 'rb').read()
        txt = MIMEText(txt_file, 'base64', 'utf-8')
        txt["Content-Type"] = 'application/octet-stream'
        txt.add_header('Content-Disposition', 'attachment', filename=file)
        msg_root.attach(txt)

    try:
        sftp_obj =smtplib.SMTP('smtp', 25)
        sftp_obj.login(sender_mail, sender_pass)
        sftp_obj.sendmail(sender_mail, to, msg_root.as_string())
        sftp_obj.quit()
        print('sendemail successful!')

    except Exception as e:
        print('sendemail failed next is the reason')
        print(e)


def get_filename(case_path):
    # 使用os.walk方法遍历得到所有文件名称filename的列表集合
    all_case_list = []
    for dirpath, dirname, filename in os.walk(case_path):
        for file in filename:
            # 此处注意,要想拿到所有的testcase必须在每个文件夹中有一个__init__.py文件引导,否则无法获取。
            # 判断文件以.py结尾且不以__开始,为去除__init.py文件和.pyx后缀的文件
            if file.endswith(".py") and not file.startswith("__"):
                # logger.info(file)
                all_case_list.append(file)
    return all_case_list

def add_case_suit(case_list):
    '''添加case'''
    logger.info("需要执行这些用例:\n%s" % case_list)
    i = 0
    sum = 0
    suit = unittest.TestSuite()
    for case in case_list:
        i += 1
        logger.info("%s %s" % (i, case))
        discover = unittest.defaultTestLoader.discover(start_dir=case_path, pattern=case)
        logger.info("%s %s %s" % (i, case, discover.countTestCases()))
        print("%s %s %s" % (i, case, discover.countTestCases()))
        sum += discover.countTestCases()
        suit.addTest(discover)
    logger.info(sum)
    print(sum)
    return suit


def run_case_suit(suit,report,host):
    '''运行所有的case'''
    run = HTMLTestRunner(title="%s自动化测试报告"%(host),
                        description="%s测试结果"%(host),
                        stream=open(report, "wb"),
                        verbosity=2,
                        # retry=1
                         )
    logger.info(suit)
    run.run(suit)



if __name__ == "__main__":

    test_dir = current_path + '/'+'testCase/testAttactPretectionIpv6/'
    report_path = current_path + '/report/'
    host = Token().host
    report = report_path + 'testreport/' + datetime.datetime.now().strftime('%m-%d_%H.%M')+"自动化测试报告%s.html"%(host)
    result = report_path + 'result/' + 'case_result.txt'
    logfile = Logger().logname


    # 1. 清空之前的结果
    modify_text(report_path=report_path )

    # 2. 获取所有的用例文件
    all_case_list = get_filename(case_path=test_dir)

    # 3.添加需要执行的用例文件
    case_list = list(set(all_case_list) - set(not_case_list))
    suit = add_case_suit(case_list=case_list)

    # 4.执行所有的case
    run_case_suit(suit=suit,report=report,host=host)

    # 5.发送邮件
    send_email_by_qq(to=['test.qq@qq.com'
                         ],
                         files=[report,result,logfile],
                         host=host)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值