繁体   English   中英

Python 在 pytest 中运行时停用 loguru.logger.catch() 函数

[英]Python deactivate loguru.logger.catch() function when run in pytest

我正在使用 loguru.logger.catch() 函数来记录一些输出。 另外,当我使用 pytest 测试我的课程时,我想停用此功能。 我试过使用猴子补丁,但没有用。 我该如何处理这种情况?

示例代码:

class DividerClass:

    @logger.catch
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

        if self.num2 == 0:
            raise ZeroDivisionError
        else:
            self.result = self.num1 / self.num2
            logger.info(f"DividerClass {self.num1} / {self.num2} = {self.result}")


def test_divider_class_with_zero(monkeypatch):
    monkeypatch.setattr(loguru.logger, "catch", lambda x: x)
    
    with pytest.raises(ZeroDivisionError):
        DividerClass(0, 0)

您可以尝试使用 loguru 禁用方法 logger.disable logger.disable(None)

根据您的代码结构,您可以传递模块的名称而不是 None 来禁用该模块的日志记录。

使用logger.enable(...)之后,您可以为其他测试重新启用日志记录。

有关更多详细信息,请参阅禁用方法的 loguru 文档

问题归结为何应用装饰器。 到测试收集完成时,装饰器已经应用于函数。 因此,我们有两种选择:

  1. 修补导入所需的对象
  2. 打补丁重新加载模块

在下面的代码中,我展示了前一种方法。 此代码还假定您的测试文件位于与实际代码不同的文件中。

# src/manager.py

from loguru import logger

class DividerClass:

    @logger.catch
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

        if self.num2 == 0:
            raise ZeroDivisionError
        else:
            self.result = self.num1 / self.num2
            logger.info(f"DividerClass {self.num1} / {self.num2} = {self.result}")


# tests/test_manager.py

import pytest
import loguru

def test_divider_class_with_zero(monkeypatch):
    monkeypatch.setattr(loguru.logger, "catch", lambda x: x)
    # notice the import happens after the patch
    from src.manager import DividerClass
    
    with pytest.raises(ZeroDivisionError):
        DividerClass(0, 0)

=============================================== test session starts ================================================
platform darwin -- Python 3.8.9, pytest-7.0.1, pluggy-1.0.0
rootdir: ***
plugins: asyncio-0.18.3, xdist-2.5.0, forked-1.4.0, hypothesis-6.48.1, mock-3.7.0
asyncio: mode=strict
collected 1 item                                                                                                   

tests/test_manager.py .                                                                                      [100%]

================================================ 1 passed in 0.02s =================================================

在此处阅读此出色答案以了解更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM