当使用固定装置创建时,Pytest caplog 可与自定义记录器配合使用,但直接在测试方法中创建时则无法使用

Zob*_*san 7 python logging pytest caplog

我一直在使用 Pytest 测试我的自定义记录器。从 Yaml 配置文件创建自定义记录器,并编写以下测试:

@pytest.fixture(scope="module")
def logger():
    """Fixture for providing a configured logger object"""
    logging_config = yaml.safe_load(config_yaml)
    logging.config.dictConfig(logging_config)
    return logging.getLogger("test_logger")


def test_logger_emits_with_queue_handler(logger, caplog):
    """Test fails if queue handler could not emit logs"""
    logger.info("This is a test")
    assert "This is a test" in caplog.text
Run Code Online (Sandbox Code Playgroud)

这有效并且测试按预期通过。

但是,当我尝试不使用固定装置时,测试失败:

def test_logger_emits_with_queue_handler(caplog):
    """Test fails if queue handler could not emit logs"""
    logging_config = yaml.safe_load(config_yaml)
    logging.config.dictConfig(logging_config)
    logger = logging.getLogger("test_logger")
    logger.info("This is a test")
    assert "This is a test" in caplog.text
Run Code Online (Sandbox Code Playgroud)

作为参考,我的配置 yaml 文件、自定义队列处理程序来自我的日志记录库

version: 1
objects:
  queue:
    class: queue.Queue
    maxsize: 1000
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    formatter: simple
    stream: ext://sys.stdout
  queue_handler:
    class: logging_.handlers.QueueListenerHandler
    handlers:
      - cfg://handlers.console
    queue: cfg://objects.queue
loggers:
  test_logger:
    level: DEBUG
    handlers:
      - queue_handler
    propagate: yes
root:
  level: NOTSET
  handlers:
    - console
Run Code Online (Sandbox Code Playgroud)

我正在尝试了解其中的原因。是因为在 Pytest 加载并运行测试方法时已经配置了标准记录器对象吗?有没有一种解决方法可以在不编写固定装置的情况下执行此操作?