我有一套python模块的单元测试,并使用Pytest来运行这些测试。我现在开始在我的库中使用标准日志库,需要帮助解决两个问题:
- 如何在运行测试套件时防止日志进入文件,防止文件增长,并防止真实日志文件中的无用条目
- 如何捕获单元测试内部的日志,以便能够对库生成的日志运行断言
我尝试测试的模块将__init__.py
中的日志库配置为登录到文件中,并使用info方法记录模块代码中的条目。这很好,当我运行代码时,正确的日志条目会出现在文件ok中。--请参阅下面的代码--
我曾尝试在pytest中使用caplog
固定装置——请参阅下面的代码和输出——,但我得到的效果是:
- 日志条目包含在文件中(使用caplog和所有其他测试运行时生成的日志(
-
caplog.text
为空
单元测试代码
import library.module
class TestFunction:
def test_something_else(self):
library.module.function():
assert True
def test_logs(self,caplog)
library.module.function():
assert "desired" in caplog.text
测试输出
(...)
> assert "desired" in caplog.text
E AssertionError: assert 'desired' in ''
E + where '' = <_pytest.logging.LogCaptureFixture object at (...).text
(...)
运行测试套件后记录条目
2021-12-07 11:10:05,915 - library.module - INFO - desired
2021-12-07 11:10:05,917 - library.module - INFO - desired
日志模块配置
__init__.py
import logging.config
import yaml
with open("logging.yaml") as f:
conf_dict = yaml.safe_load(f)
logging.config.dictConfig(conf_dict)
logging.yaml
version: 1
formatters:
simple:
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
training:
class: logging.FileHandler
level: DEBUG
formatter: simple
filename: logs/test_log
loggers:
library.module:
level: DEBUG
handlers: [training]
propagate: no
root:
level: DEBUG
handlers: []
被测模块
import logging
logger = logging.getLogger(__name__)
def function():
logger.info("desired")
文件结构
.
├── library
│ ├── module.py
│ └── __init__.py
├── tests
│ └── test_module.py
└── logs
└── test_log
为了避免写入日志文件,我建议在test_module.py
中,您只需模拟记录器并在测试中使用它,如下所示:
import pytest
import library.module
@pytest.fixture
def logger(mocker):
return mocker.patch("library.module.logger.info")
class TestFunction:
def test_something_else(self):
library.module.function():
assert True
def test_logs(self,logger)
library.module.function():
logger.assert_called_with("desired")