Pytest allure中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中的日誌。

 

獻給有需要的人。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章