首页 > 其他分享 >Pytest allure中steps中添加日志

Pytest allure中steps中添加日志

时间:2023-08-22 10:34:09浏览次数:39  
标签:info logging allure plugin handler step Pytest steps

是否在使用allure时,为了更好的定位问题,会把日志添加上去。类似如下的情行:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/7/18 9:12
# @Author  : huzq
# @File    : test_allure.py
import logging

import allure
import pytest

LOG = logging.getLogger(__name__)


def test_example(testfixture):
    with allure.step("First step"):
        LOG.info("There is first step")

    LOG.info("Between steps")

    second = "second"
    with allure.step("Second step"):
        LOG.info("There is %s step", second)
        LOG.info("Another message in second step")

    with allure.step("Outer step"):
        LOG.info("First line outer step")
        LOG.info("Seconds line outer step")
        with allure.step("Inner step"):
            LOG.info("First line for inner step")
            LOG.info("Second line for inner step")
        LOG.info("Lets close outer step with another line")

def test_print():
    ssss()
    ssss2()
    pytest.assume(1==2)

    logging.info("Logging an info message")
    logging.debug("Logging a DEBUG message")
    logging.warning("Sample time is too low!")
    raise Exception

def test_print22():
    ssss()
    ssss2()
    pytest.assume(1==2)

    logging.info("Logging an info message")
    logging.debug("Logging a DEBUG message")
    logging.warning("Sample time is too low!")
    raise Exception

@allure.step('first step')
def ssss():
    logging.info('this is the first step')

@allure.step('2 step')
def ssss2():
    logging.info('this is the first step')

执行后,allure显示的日志如下:

有step,有日志。

 是不是感觉还行。但问题来了,一旦日志多了怎么定位问题。要是能在step中将这个step的日志显示出来就更好了。

解决方案:

翻遍了allure及pytest的API文档,倾情奉献:

只需要在conftest.py中加入如下代码:

class AllureLogStep:
    def __init__(
        self, capture_handler: _pytest.logging.LogCaptureHandler = None
    ):
        self._capture_handler = capture_handler
        self._io_stack = []

    @allure_commons.hookimpl
    def start_step(self, uuid, title, params):
        if self._capture_handler:
            stream = self._capture_handler.setStream(io.StringIO())
            self._io_stack.append(stream)

    @allure_commons.hookimpl
    def stop_step(self, uuid, exc_type, exc_val, exc_tb):
        if self._capture_handler:
            previous_stream = self._io_stack.pop()
            stream = self._capture_handler.setStream(previous_stream)
            step_logs = stream.getvalue().strip()
            allure.attach(
                step_logs,
                name="log",
                attachment_type=allure.attachment_type.TEXT,
            )


@pytest.hookimpl(trylast=True)
def pytest_configure(config: _pytest.config.Config):
    logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
    handler = _pytest.logging.LogCaptureHandler()
    handler.setFormatter(logging_plugin.formatter)
    handler.setLevel(logging_plugin.log_level)

    logger = logging.getLogger()
    logger.addHandler(handler)

    step_plugin = AllureLogStep(handler)
    allure_commons.plugin_manager.register(step_plugin)

    def unregister_plugin(plugin):
        def unregister():
            allure_commons.plugin_manager.unregister(plugin)

        return unregister

    config.add_cleanup(unregister_plugin(step_plugin))

再次执行用例,结果就会如下:

 看,步骤中是不是有log文件了。而且还是单独的step中的日志。

 

献给有需要的人。

标签:info,logging,allure,plugin,handler,step,Pytest,steps
From: https://www.cnblogs.com/landhu/p/17647872.html

相关文章

  • 记:pycharm无法使用pytest运行文件
     工作当中遇到无法通过pytest进行运行脚本当前setting里面也设置了,但是还是无法进行运行。原因:进入了python 运行的模式了,脚本在运行的时候会通过python默认运行脚本。 解决方式:运行按钮旁边有个编辑入口   然后就会按照你设置的运行方式去执行脚本了 ......
  • pytest+yaml测试用例
    #一、yaml格式##yaml是一种数据类型,可以和json之间灵活的切换,支持注释、换行、字符串等。可以用于配置文件或编写测试用例。##数据结构:一般是键值对的方式出现。注意编写时值前面必须有空格,键:(空格)值。##如果是数组,以-(空格)开头来表示##以user.yaml为例,这里编写两个用例,每个用......
  • python+allure生成测试报告
    #一、allure安装##下载地址:CentralRepository:io/qameta/allure/allure-commandline(apache.org)##下载需要安装的版本,这里我选择的是2.9的版本##图片##下载解压完成后,将bin文件夹所在的目录放入环境变量中,同时需要安装JDK。##完成后,命令行pipinstallallure-pytest安装......
  • pytest + yaml 框架 -53.yaml 用例规范与全部关键字总结
    前言v1.4.4版本新增对yaml用例格式校验,不合法的用例格式不会被执行,避免出现用例格式不合法导致的报错。全部关键字总结config中可用关键字关键字可支持类型功能说明name可选str没什么用,仅描述当前yaml用例的名称base_url可选str,支持格式:http://、htt......
  • 软件测试|docker搭建Jenkins+Python+allure自动化测试环境
    简介本文将详细介绍如何使用Docker搭建一个完整的自动化测试环境,其中包括Jenkins作为持续集成和持续交付工具,Python作为测试脚本编写语言,以及Allure作为测试报告生成工具。通过使用Docker容器,您可以轻松地设置和管理这些工具,提高测试效率和质量。安装docker安装docker的步骤,可以直......
  • 解决Pycharm运行成功,但无法生成:pytest-html报告
    不生成报告的原因:用户习惯:使用者习惯于单独执行测试文件.py,调试测试用例;而编辑器为了方便用户执行测试用例,变调用pythontest来执行测试用例,这种情况下,执行的只是用例或者套件,不是整个文件,即main里面输出报告的语句没有执行,变不会生成测试报告;解决方法:如下图:1.全局执行;2.执......
  • WEB自动化-Allure报告-添加日志内容到Allure报告
    如果想把LOG内容输出到Allure报告,步骤如下:1、创建pytest.ini文件,设置规则 2、创建conftest文件,设置driver和日志封装及截图#浏览器驱动importloggingimportallureimportpytestfromseleniumimportwebdriverfromselenium.webdriver.chrome.optionsimportOpti......
  • WEB自动化-Allure报告的自定义
    生成了Allure报告,可以自定义一些属性,使报告看起来层级更明显,看起来更清晰。下图显示有些优化的选项 创建测试用例:importallure#importlogging#logging.basicConfig(level=logging.INFO)@allure.epic("测试版本:V1.1")@allure.feature("首页模块")@allure.title("......
  • WEB自动化-Allure报告-使用钩子函数 进行失败截图
    Allure报告中支持使用钩子函数进行失败截图   使用pytest_runtest_makereport钩子函数实现allure报告添加用例失败截图(函数名固定的) Hook函数又称为钩子函数,它的作用可以理解成钩住自己喜欢的东西(在window中,喜欢的东西可理解为消息),然后对自己喜欢的东西单独做处理 ......
  • WEB自动化-Allure报告-Allure安装和简单用法
    WEB自动化测试可以借助Allure生成美观的测试报告。1、安装工具及配置环境变量1.安装JDK1.8才可运行allure,直接百度,一大堆2.下载Allure的安装包(版本号:2.13.5)https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/3.解压Allure压缩包......