Python、py.test 和 stderr——从 Cement 日志扩展中捕获日志处理程序输出
Python, py.test and stderr -- capturing logging handler output from Cement logging extension
我在 Python 中开发了一个应用程序,并且正在使用 Cement CLI 库。我正在使用 py.test
和 CementTestCase
。我可以在测试用例中毫无问题地捕获 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
但是,在尝试使用相同的机制捕获 Cement
日志扩展的 stderr
输出时,没有捕获任何内容(回复:将 'stdout' 替换为 'stderr'以上代码)。我看到了一种迭代标准 Python 日志处理程序以查找输出的方法,我怀疑类似的东西会被使用 Cement
日志扩展来捕获 stderr
,但我有麻烦搞清楚。有人有任何见解吗?
可以使用 capsys
夹具捕获 stdout
或 stderr
输出。
然后您可以像这样进行检查(示例改编自文档):
def test_myoutput(capsys):
print("hello")
sys.stderr.write("world\n")
captured = capsys.readouterr()
assert captured.out == "hello\n"
assert captured.err == "world\n"
为了更精细,您可以使用 caplog
固定装置。这将使您能够访问日志级别、记录器等,而不仅仅是文本行。这取决于您提到的依赖标准库的 logging
模块的扩展,因此它可能不可用。
您可以使用该固定装置执行的操作的示例(再次归功于 pytest 文档):
def test_baz(caplog):
func_under_test()
for record in caplog.records:
assert record.levelname != 'CRITICAL'
assert 'wally' not in caplog.text
我在 Python 中开发了一个应用程序,并且正在使用 Cement CLI 库。我正在使用 py.test
和 CementTestCase
。我可以在测试用例中毫无问题地捕获 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
但是,在尝试使用相同的机制捕获 Cement
日志扩展的 stderr
输出时,没有捕获任何内容(回复:将 'stdout' 替换为 'stderr'以上代码)。我看到了一种迭代标准 Python 日志处理程序以查找输出的方法,我怀疑类似的东西会被使用 Cement
日志扩展来捕获 stderr
,但我有麻烦搞清楚。有人有任何见解吗?
可以使用 capsys
夹具捕获 stdout
或 stderr
输出。
然后您可以像这样进行检查(示例改编自文档):
def test_myoutput(capsys):
print("hello")
sys.stderr.write("world\n")
captured = capsys.readouterr()
assert captured.out == "hello\n"
assert captured.err == "world\n"
为了更精细,您可以使用 caplog
固定装置。这将使您能够访问日志级别、记录器等,而不仅仅是文本行。这取决于您提到的依赖标准库的 logging
模块的扩展,因此它可能不可用。
您可以使用该固定装置执行的操作的示例(再次归功于 pytest 文档):
def test_baz(caplog):
func_under_test()
for record in caplog.records:
assert record.levelname != 'CRITICAL'
assert 'wally' not in caplog.text