如何将stdlib日志记录与py.test结合使用

por*_*uod 6 python logging unit-testing pytest

我正在使用py.test来测试我的一些模块,其中包含相当多的stdlib日志记录.我当然喜欢将日志记录到stdout,这是由py.test捕获的,因此如果测试失败,我将获得所有相关的日志消息.

这样做的问题是,在py.test 丢弃此对象之后,日志记录模块最终尝试将消息记录到py.test提供的'stdout'对象.也就是说,我得到:

Traceback (most recent call last):
  File "/usr/lib/python2.6/atexit.py", line 24, in _run_exitfuncs
    func(*targs, **kargs)
  File "/usr/lib/python2.6/logging/__init__.py", line 1508, in shutdown
    h.flush()
  File "/usr/lib/python2.6/logging/__init__.py", line 754, in flush
    self.stream.flush()
ValueError: I/O operation on closed file
Run Code Online (Sandbox Code Playgroud)

如果我关闭捕获-s,我没有任何问题,但当然这使得测试输出与不相关的日志记录无法读取.

谁能告诉我将stdlib日志记录与py.test集成的正确方法?

(我试着看看这个,它看起来应该只是没有问题,所以它对我帮助不大)

hpk*_*k42 6

记录/捕获交互是为了更好地使用即将发布的2.0.1版本,您可以通过以下方式将其作为开发快照安装:

pip install -i http://pypi.testrun.org pytest 
Run Code Online (Sandbox Code Playgroud)

之后输入"py.test --version"时,你应该至少得到"2.0.1.dev9".而你发布的问题/错误现在应该消失了.

一点背景:日志包坚持"拥有"它使用的流,默认情况下它抓取sys.stderr并坚持在进程退出时关闭它,通过atexit模块注册.py.test用一个临时文件替换sys.stdout以便快照输出(包括在文件描述符级别的输出以便也捕获子进程输出).所以py.test进化到非常小心,总是使用相同的临时文件,因为没有日志记录的atexit-code抱怨.

并不是说你也可以安装[pytest-capturelog] [1]插件,这将有助于处理日志输出.

[1] http://pypi.python.org/pypi/pytest-capturelog/0.7