[英]Python, py.test and stderr — capturing logging handler output from Cement logging extension
I have developed an application in Python and am using the Cement CLI library.我已经用 Python 开发了一个应用程序,并且正在使用 Cement CLI 库。 I am using
py.test
with the CementTestCase
.我使用
py.test
与CementTestCase
。 I can capture the output from stdout
in the test cases without a problem, using something like this:我可以毫无问题地捕获测试用例中
stdout
的输出,使用如下所示:
with EZOTestApp(argv=['view', 'deploys']) as app:
old_stdout = sys.stdout
app.ezo = EZO(app.config["ezo"])
result = StringIO()
sys.stdout = result
app.run()
output = sys.stdout.getvalue()
sys.stdout = old_stdout
assert 'deploy' in output
However, in attempting to trap the stderr
output from the Cement
logging extension using the same mechanism captures nothing (re: replacing 'stdout' with 'stderr' in the above code).然而,在尝试使用相同的机制捕获来自
Cement
日志扩展的stderr
输出时,什么也没有捕获(re:在上面的代码中用 'stderr' 替换 'stdout' )。 I saw a method for iterating through the standard Python logging handlers for finding the output, and I suspect something similar would be used the Cement
logging extension to capture stderr
, but I'm having trouble figuring it out.我看到了一种遍历标准 Python 日志处理程序以查找输出的方法,我怀疑会使用类似的东西
Cement
日志扩展来捕获stderr
,但我无法弄清楚。 Anyone have any insight?任何人都有任何见解?
Capturing the stdout
or stderr
output can be done with the capsys
fixture.捕获
stdout
或stderr
输出可以使用capsys
夹具完成。
You can then make checks like this (example adapted from the docs):然后,您可以进行这样的检查(根据文档改编的示例):
def test_myoutput(capsys):
print("hello")
sys.stderr.write("world\n")
captured = capsys.readouterr()
assert captured.out == "hello\n"
assert captured.err == "world\n"
For even more granularity, you can use the caplog
fixture.为了获得更多的粒度,您可以使用
caplog
固定装置。 This one will give you access to the log level, the logger, etc., as opposed to the text line only.这将使您能够访问日志级别、记录器等,而不仅仅是文本行。 This depends on the extension you mention relying on the standard lib's
logging
module though, so it might no be available.这取决于您提到的依赖于标准库的
logging
模块的扩展,因此它可能不可用。
An example of what you can do with that fixture (again, credit goes to the pytest doc):您可以使用该夹具做什么的示例(同样,归功于 pytest 文档):
def test_baz(caplog):
func_under_test()
for record in caplog.records:
assert record.levelname != 'CRITICAL'
assert 'wally' not in caplog.text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.