【问题标题】:Pytest: best practices for logging using allurePytest:使用 allure 进行日志记录的最佳实践
【发布时间】:2020-12-20 13:03:14
【问题描述】:

现在我正在尝试找出记录 pytest 的最佳方式。我将为此使用诱惑力。记录每个包含的所有函数调用对我来说很重要:

  • 函数参数
  • 返回结果
  • 时间戳(可选)

例如,我可以这样做:

import allure


@allure.step("The sum of two numbers")
def my_sum(a, b):
    result = a + b
    with allure.step("Result: {}".format(result)):
        pass
    return result


def test_sum():
    observed = my_sum(1, 2)
    assert observed == 3

日志:

对我来说,日志看起来不错,但代码看起来很难看。

第二种方式:

import allure


@allure.step("The sum of two numbers")
def my_sum(a, b):
    result = a + b
    allure.attach(str(result), 'Result', allure.attachment_type.TEXT)
    return result


def test_sum():
    observed = my_sum(1, 2)
    assert observed == 3

日志:

Log 看起来有点差,不过还好。在这种情况下,将为每个附件创建单独的文件。恐怕会为大型日志创建大量附件,并且报告会运行缓慢。

此外,在这两种情况下,我都需要为每个函数添加大量代码 + 为我的代码添加时间戳看起来很难看。

请分享您使用 allure 进行日志记录的最佳实践。

附:在我使用 Robot Framework 之前,该框架中的上述代码如下所示:

*** Settings ***


*** Test Cases ***
Test Sum
    ${observed}    My Sum    1    2
    Should Be Equal As Strings    ${observed}    3


*** Keywords ***
My Sum
    [Arguments]    ${a}    ${b}
    ${result}    Evaluate    ${a} + ${b}
    [Return]    ${result}

日志:

理想情况下,我希望得到这样的日志。日志包含参数、返回的结果、函数内部的所有步骤和时间戳。

【问题讨论】:

    标签: python pytest allure


    【解决方案1】:

    我不确定我是否有一个解决方案可以轻松地让您的日志看起来完全像机器人框架的日志,但我有一些提示给您:

    1. 您不必为 @allure.step 装饰器提供任何消息,您可以将其留空,然后 allure 将获取名称和参数并为您打印。

    2. 您可以通过这种方式将 allure 日志处理程序添加到您的记录器: 在你的 conftest.py 中:

       def pytest_runtestloop(session) -> None:
           allure_logger = AllureLogger()
           if allure_logger not in logger.handlers:
               logger.info('Adding Allure logger')
               logger.addHandler(allure_logger)
      

      在另一个文件 allure_log_handler.py(或任何你想要的)中:

       class AllureLogger(logging.Handler):
           def emit(self, record):
               if logging.DEBUG < record.levelno:  # print to allure only "info" messages
                   with allure.step(f'LOG ({record.levelname}): {record.getMessage()}'):
                       pass  # No need for content, since the step context is doing the work.
      

      现在所有的“信息”日志都会被打印出来,可以稍微清理一下你的代码。

    3. 您可以使用自己的装饰器包装 allure.step 并使用 timeit 或其他一些计时库来检查方法执行花费了多少时间并将其打印到您的日志中。

    4. 只要您打印到记录器,您就不需要allure.attach(str(result), 'Result', allure.attachment_type.TEXT)。 allure 可以自动为您附加 - 方法如下:How to append logs of Pytest into Allure Report

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      • 2021-08-05
      • 2010-10-08
      相关资源
      最近更新 更多