Python 记一次 python+allure 的学习

tangoliver · 2023年02月28日 · 3595 次阅读

1、allure 下载

地址:https://github.com/allure-framework/allure2/releases

下载完成后,配置 window 的环境变量,到 bin 目录

配置完成后,cmd 命令窗口输入以下命令,检查是否安装成功

allure --version

基本用法

# Allure监听器在测试执行期间会收集结果,只需添加alluredir选项,并选择输出的文件路径即可。
pytest --alluredir=./allure-results

# 执行此命令,将在默认浏览器中显示生成的报告
allure serve ./allure-results

# 命令行输入allure generate -c -o allure-reports,即可在当前路径下生成测试报告 (-c:清空历史数据,-o:指定输出测试报告路径)
# 使用allure serve allure-results,则会在系统默认目录下生成测试报告

Allure 注解说明

2、安装依赖包

pip3 install allure-pytest
pip3 install pytest_html
pip3 install pytest

3、使用

# test_allure.py

def run(*args):
    # 测试用例目录
    alluredir = os.path.join(GetPathInfo().get_project_path(), 'reports', 'allure_raw')
    allure_report = os.path.join(GetPathInfo().get_project_path(), 'reports', 'allure_report')
    htmldir = os.path.join(GetPathInfo().get_project_path(), 'reports', 'html')
    # 执行参数
    param = ['-s', '-v',
        '--cache-clear', # 清除缓存
        f'--html={htmldir}/report.html', # 生成html报告
        f'--alluredir={alluredir}', # 生成allure报告
    ]

    try:
        for i in args:
            param.append(i)  # 添加指定执行测试脚本列表
    except IndexError as e:
        log.error(e)
        log.error('自定义测试套件不存在')

    print('param=', param)
    pytest.main(param)  # 执行测试
    os.system(f'allure generate {alluredir} -o {allure_report} --clean')  # 通过allure插件,生成测试报告

if __name__ == '__main__':
    path = os.path.join(GetPathInfo().get_project_path() + 'demo', 'CASE02_WORK')
    run(path)

# get_path_info.py

import os
class GetPathInfo:
    def get_project_path(self):
        """ 获取项目根路径 """
        return os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] + "\\"

# get_logger.py

class GetLogger(object):
    @classmethod
    def get_logger(clsc):
        log = logging.getLogger(__name__)  # 不会打印 HTTP General 信息
        # log = logging.getLogger()
        level_relations = {
            'NOTSET': logging.NOTSET,
            'DEBUG': logging.DEBUG,
            'INFO': logging.INFO,
            'WARNING': logging.WARNING,
            'ERROR': logging.ERROR,
            'CRITICAL': logging.CRITICAL
        }  # 日志级别关系映射

        # 创建日志存放的目录
        project_path = GetPathInfo().get_project_path()  # get_project_path()获取项目根目录

        logs_dir = project_path + "logs"
        if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
            pass
        else:
            os.mkdir(logs_dir)
        # 日志文件以日期命名
        log_file_name = '%s.log' % time.strftime("%Y-%m-%d", time.localtime())
        log_file_path = os.path.join(logs_dir, log_file_name)

        rotating_file_handler = handlers.TimedRotatingFileHandler(filename=log_file_path,
                                                                  when='D',  # 按天分隔,一天一个文件
                                                                  interval=30,
                                                                  encoding='utf-8')
        log_colors_config = {'DEBUG': 'white',
                             'INFO': 'cyan',
                             'WARNING': 'yellow',
                             'ERROR': 'red',
                             'CRITICAL': 'bold_red'}
        # 日志输出格式
        fmt = "%(asctime)s %(levelname)s %(pathname)s [%(lineno)d]:%(message)s"
        # fmt = "%(name)s %(asctime)s %(created)f %(relativeCreated)d %(msecs)d %(levelname)s %(levelno)s %(pathname)s %(filename)s %(module)s %(funcName)s %(lineno)d %(process)d %(thread)d %(threadName)s %(message)s"
        # formatter = logging.Formatter(fmt)
        formatter = ColoredFormatter(fmt)
        rotating_file_handler.setFormatter(formatter)

        # 加上判断,避免重复打印日志
        if not log.handlers:
            # 控制台输出
            console = logging.StreamHandler()
            console.setLevel(level_relations["NOTSET"])
            console.setFormatter(formatter)
            # 写入日志文件
            log.addHandler(rotating_file_handler)
            log.addHandler(console)
            log.setLevel(level_relations['DEBUG'])
        return log

4、执行完后,会再 report 目录下,生成测试报告


可以通过浏览器,直接打开 allure_report 目录下的 index.html,文件查看测试报告

另外,也可以通过执行命令,查看测试报告

allure open [报告目录]
allure open .\reports\allure_report 

注:直接打开报告的 index.html 文件,有可能会出现 loading 或者 404(如下图),所以最好使用命令方式打开
allure open [报告目录]

暫無回覆。
需要 登录 後方可回應,如果你還沒有帳號按這裡 注册