mik*_*ike 5 python doctest pytest python-3.x
我们正在使用pytestpython std logging,并在 s 中进行一些测试doctest。我们希望能够使log_cliide 中的调试测试变得更容易(让我们stderr流向“实时”控制台,这样人们就可以看到单步执行时输出的日志语句)问题是“使用”之间似乎存在错误/迭代”(例如logging存在对等的调用logger.info("..."))log_cli=true。
我在文档中没有看到任何其他标志或提及这一点,因此它似乎是一个错误,但希望有一个解决方法。
该测试模块通过:
# bugjar.py
"""
>>> dummy()
'retval'
"""
import logging
logger = logging.getLogger(__name__)
def dummy():
# logger.info("AnInfoLog") ## un-comment to break test
return "retval"
Run Code Online (Sandbox Code Playgroud)
但取消注释(没有其他更改)调用logger.info(会导致失败:(除非我log_cli从中删除pytest.ini)
002 >>> dummy()
Expected:
'retval'
Got nothing
Run Code Online (Sandbox Code Playgroud)
这是我的命令行和相关版本输出:
(venv) $ ./venv/bin/pytest -c ./pytest.ini ./bugjar.py
======================================================================= test session starts ========================================================================
platform linux -- Python 3.8.5, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: -omitted-/test-unit, configfile: ./pytest.ini
plugins: forked-1.3.0, xdist-2.2.1, profiling-1.7.0
collected 1 item
bugjar.py::bugjar
bugjar.py::bugjar
-------------------------------------------------------------------------- live log call ---------------------------------------------------------------------------
INFO bugjar:bugjar.py:8 AnInfoLog
FAILED [100%]
============================================================================= FAILURES =============================================================================
_________________________________________________________________________ [doctest] bugjar _________________________________________________________________________
001
002 >>> dummy()
Expected:
'retval'
Got nothing
Run Code Online (Sandbox Code Playgroud)
和我的pytest.ini(注意,注释是正确的,通过/失败不受使用日志文件或其他 addopts 的影响
[pytest]
addopts = --doctest-modules # --profile --profile-svg
norecursedirs = logs bin tmp* scratch venv* data
# log_file = pytest.log
log_cli = true
log_cli_level=debug
Run Code Online (Sandbox Code Playgroud)
删除log_cli*frompytest.ini会使问题消失。
这似乎显然与log_cli捕获输出以供文档测试本身使用的操作相关,但也不是预期的行为。
我希望我犯了一个错误,或者有一种解决方法可以在bashIDE shell 窗口/调试器中获取实时日志输出。
抱歉Y4Kman从 GitHub重新发布了您的解决方案(请自行发布,我将删除我的解决方案):
解决此问题的一种方法是使用pytest_runtest_call挂钩禁用 doctest 项目的捕获:
import sys
from _pytest.config import hookimpl
from _pytest.doctest import DoctestItem
from _pytest.nodes import Item
@hookimpl(hookwrapper=True)
def pytest_runtest_call(item: Item) -> None:
"""Hook to suspend global capture when running doctests"""
if isinstance(item, DoctestItem):
capman = item.config.pluginmanager.getplugin('capturemanager')
if capman:
capman.suspend_global_capture(in_=True)
out, err = capman.read_global_capture()
sys.stdout.write(out)
sys.stderr.write(err)
yield
Run Code Online (Sandbox Code Playgroud)