所以我有一个测试文件夹结构(测试模块
src
此处未显示),如下所示:
├── tests
│ ├── __init__.py
│ ├── conftest.py
│ ├── test_main.py
并让
__init__.py
配置我的日志记录,如下所示:
import structlog, logging, sys
from structlog.testing import LogCapture
logging.basicConfig(filename="test.log", filemode="w")
structlog.configure(
processors=[LogCapture()],
context_class=structlog.threadlocal.wrap_dict(dict),
logger_factory=structlog.stdlib.LoggerFactory(),
cache_logger_on_first_use=True
)
我的
test_main.py
如图所示:
import logging, structlog, pytest
from src.factories.factories import MyFactory
import src.main
from pathlib import Path
from datetime import datetime
@pytest.mark.parametrize(
"factory",
[
MyFactory(),
],
)
def test_main(path_to_results_folder_fixture_in_conftest, factory):
structlog.get_logger().info("test")
no_of_files_function = lambda: sum(1 for _ in Path(path_to_results_folder_fixture_in_conftest).iterdir())
len_before = no_of_files_function()
src.main.main("sony", factory, path_to_results_folder)
assert no_of_files_function() == len_before + 1
然后我只需运行
pytest test_main.py
。我期待 structlog.get_logger().info("test")
线在 test
中产生 test.log
线。然而,只生成了一个空的test.log
。我究竟做错了什么?我已经配置了日志记录,但 structlog 似乎没有看到它。有关更多信息,也不会向 stdout/console 输出任何内容。
如果您将
structlog
配置为使用 LogCapture
,它会捕获日志条目而不是打印它们 - 这就是它的全部目的。另请参阅https://www.structlog.org/en/latest/testing.html
默认情况下,pytest 捕获所有输出并仅在失败的测试中显示它。设置 capture=no 或简称 -s 可能会解决您的问题。
尝试
pytest -s test_main.py
或者如果使用 pytest.ini
[pytest]
addopts = -s