py.test 未使用终端 % 完成而终止

py.test terminates without completing with a terminal %

我是第一次使用 pytest,主要是它很棒,但有时它只是终止而没有完成,没有错误消息。

=========================================================================================== test session starts ============================================================================================
platform darwin -- Python 3.5.1, pytest-2.8.5, py-1.4.31, pluggy-0.3.1
rootdir: /Users/dacre/mike_tools/python, inifile:
collected 7 items

test_pipeline.py ......F%

在发布这个问题的过程中,我弄明白了,但我将其发布在这里,以供遇到相同问题的其他人使用。

问题在于您的代码是否意外地在 sys.stderrsys.stdout 上调用了 close()。这发生在我身上是因为我有一个日志记录功能,它试图通过 .name 属性将 sys.stderr 与不同的文件句柄区分开来。 py.test 控制了 sys.stderr 并将其重新映射到 _pytest.capture.EncodedFile 对象。因此,我的函数误解了它,并在该对象上调用了 close() 。这导致没有错误地提前终止。

我只是重写了我的代码以避免这个问题,但是另一种选择是从 sys 导入模块,然后在模块中测试 'pytest':

from sys import modules
if 'pytest' in modules:
    do something...