El marco de automatización de Appium ejecuta casos de prueba de 0 a 1 y genera informes de prueba y envía correos electrónicos

Al igual que el selenio, se requiere HTMLTestRunner.py para ejecutar casos de prueba.

1. Ejecute casos de prueba y genere informes de prueba

Directamente en el código:

TestRunnerToReport.py

# -*- coding: utf-8 -*-
"""
@ auth : carl_DJ
@ time : 2020-7-10
"""

import unittest
import HTMLTestRunner
import  time
import logging
import sys


'''
这个文件,只执行以下两个步骤:
1.执行用例
2.保存报告
'''
#测试用例文件路径
test_dir = '../test_case'
#测试报告文件路径
report_dir = '../report/'

#获取当前时间
now = time.strftime('%Y-%m-%d %H_%M_%S',time.localtime(time.time()))

#生成测试报告文件格式
report_name = report_dir + now +'test_report.html'

#加载测试用例
# discover = unittest.defaultTestLoader.discover(test_dir,pattern='test_login.py')
discover = unittest.defaultTestLoader.discover(test_dir,pattern='test*.py')

#生成并运行测试用例
with open(report_name,'wb') as f:
    runner = HTMLTestRunner.HTMLTestRunner(stream=f, title=" xxx项目移动APP Test Report", description=" Andriod app Test Report")
    logging.info('start run testcase')
    runner.run(discover)

2. Ejecute casos de prueba, genere informes y envíe correos electrónicos

2.1 Configuración de la información del buzón

2.1.1 Configurar la información de correo electrónico en el archivo yaml

email.yaml

smtp_server: smtp.qq.com
port: 465

#sender: [email protected]
#psw: carl_dj

sender: carl_dj@xx.com
psw: carl_dj

subject: xxx项目APP自动化测试报告

receiver: xiaoyu1@xx.com,xiaoyu2@xx.com

2.2.2 Configurar variables globales

Escriba toda la información de la dirección en un archivo python y lea
golbalparm.py directamente cuando lo use

# -*- coding:utf-8 -*-
"""
@ auth : carl_DJ
@ time : 2020-7-10
"""

import os

#获取项目根目录地址
 cur_path = os.path.dirname(os.path.abspath('.'))
# print(cur_path)
#测试用例地址
test_case_path = os.path.join(cur_path,'test_case')
# print(test_case_path)
#线上数据文件地址
formal_data_path = os.path.join(cur_path,'data\\formal_data\\')
# print(formal_data_path)
#测试数据文件地址
test_data_path = os.path.join(cur_path,'data\\test_data\\')
# print(test_data_path)
#截图地址
# test_screenshot_path = os.path.join(cur_path,'report\\img\\')
# print(test_screenshot_path)
#测试报告地址
test_report_path = os.path.join(cur_path,'report\\testreport')
# print(test_report_path)
#日志地址
test_log_path = os.path.join(cur_path,'report\\logs')
# print(test_log_path)
#保存截图地址
test_img_path = os.path.join(cur_path,'report\\img')
print(test_img_path)
#浏览器驱动地址
dirver_path = os.path.join(cur_path,'driver')
# print(dirver_path)
#config文件地址
config_path = os.path.join(cur_path,'config')
# print(config_path)

Si no comprende el módulo del sistema operativo, puede hacerlo directamente con Baidu.

2.2 Enviar informe de prueba por correo electrónico

Este archivo .py contiene 4 pasos:
>> Paso 1: Cargue el caso de uso
>> Paso 2: Ejecute el caso de uso
>> Paso 3: Obtenga el último informe de prueba
>> Paso 4: Envíe un correo electrónico

A continuación, veremos directamente el código:

TestRunnerToEmail.py

# -*- coding:utf-8 -*-
"""
@ auth : carl_DJ
@ time : 2020-7-10
"""

import os
import unittest
import time
import HTMLTestRunner
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from config import globalparam
from public.common.log import Logger
from public.common.get_email_parameter import GetEmailParameter

"""
执行用例并发送报告,分四个步骤:
第一步:加载用例
第二步:执行用例
第三步:获取最新的测试报告
第四步:发送邮件
"""


# 获取当前脚本的真实路径

# cur_path =os.path.dirname(os.path.abspath('.'))
log = Logger(logger='run').getlog()

def add_case( rule='test*.py'):
    '''
    作用:加载所有测试用例
    :param caseName:
    :param rule:
    :return:
    '''

    test_suite = globalparam.test_case_path
    discov = unittest.defaultTestLoader.discover(test_suite,pattern=rule)
    return discov
    # case_path = os.path.join(globalparam.test_case_path,caseName)
    # if not os.path.exists(case_path):os.mkdir(case_path)
    # 定义discover方法的参数(执行全部用例)
    # discover = unittest.defaultTestLoader.discover(case_path, pattern=rule, top_level_dir=None)
    # return discover


def run_case(all_case, reportName=''):

    '''
    作用:执行所有的用例,并把执行结果写入HTML测试报告中
    :param all_case:
    :param reportName:
    :return:
    '''
    now = time.strftime('%Y-%m-%d_%H_%M_%S', time.localtime(time.time()))
    report_path = os.path.join(globalparam.test_report_path,reportName)
    if not os.path.exists(report_path):os.mkdir(report_path)
    report_abspath = os.path.join(report_path, now + 'xx项目web自动化测试报告.html')
    with open(report_abspath, 'wb') as fp:
        runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='xx项目web自动化测试报告', description='用例执行情况')
        runner.run(all_case)


def get_report_file(report_path):
    '''
    作用: 获取最新的测试报告
    :param report_path:
    :return:
    '''
    lists = os.listdir(report_path)
    lists.sort(key=lambda fn:os.path.getmtime(os.path.join(report_path, fn)))
    print('最新测试报告:' + lists[-1])
    # 找到最新的测试报告文件
    report_file = os.path.join(report_path, lists[-1])
    return report_file


def send_mail(subject, sender, psw, receiver, smtpserver, report_file, port):
    """
    作用:将最新的测试报告通过邮件进行发送
    :param sender:发件人
    :param psw:QQ邮箱授权码
    :param receiver:收件人
    :param smtpserver:QQ邮箱服务
    :param report_file:
    :param port:端口
    :return:
    """
    with open(report_file, 'rb') as f:
        mail_body = f.read()
    # 定义邮件内容
    msg = MIMEMultipart()
    body = MIMEText(mail_body, _subtype='html', _charset='utf-8')
    msg['Subject'] = subject
    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= "WebUIAutoFramework_report.html"'
    msg.attach(att)
    try:
        smtp = smtplib.SMTP_SSL(smtpserver, port)
    except:
        smtp = smtplib.SMTP()
        smtp.connect(smtpserver, port)
    # 用户名和密码
    smtp.login(sender, psw)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
    log.info('测试报告邮件发送成功')

if __name__ == '__main__':
    # 加载用例
    all_case = add_case()
    # 执行用例
    run_case(all_case)
    # 获取最新的测试报告
    report_path =globalparam.test_report_path
    # report_path = os.path.join(config.cur_path,'report\\testreport')
    report_file = get_report_file(report_path)

    # 邮箱配置
    subject = GetEmailParameter().email_parameter()['subject']
    sender = GetEmailParameter().email_parameter()['sender']
    psw = GetEmailParameter().email_parameter()['psw']
    smtp_server = GetEmailParameter().email_parameter()['smtp_server']
    port = GetEmailParameter().email_parameter()['port']
    receiver = GetEmailParameter().email_parameter()['receiver'].split(',')
    send_mail(subject, sender, psw, receiver, smtp_server, report_file, port)

Bueno, originalmente, el código enviado por correo electrónico no quería mostrarse aquí, porque en el tutorial se ha escrito el marco de selenio de 0 a 1.
Sin embargo, Xiaoyu considera ahorrar tiempo y energía para todos, y también puede hacer comparaciones. ¡Solo escribe una vez!

Ah, claro, a continuación, compartiré la dirección del código fuente en github : portal de github.
A continuación, tengo que practicar mucho y esforzarme por convertirme en un dios lo antes posible. !

Supongo que te gusta

Origin blog.csdn.net/wuyoudeyuer/article/details/107246719
Recomendado
Clasificación