gpt4 book ai didi

Python、py.test 和 stderr——从 Cement 日志扩展中捕获日志处理程序输出

转载 作者:行者123 更新时间:2023-12-04 15:59:13 25 4
gpt4 key购买 nike

我用 Python 开发了一个应用程序,并且正在使用 Cement CLI 库。我将 py.testCementTestCase 一起使用。我可以在测试用例中毫无问题地捕获 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 捕获 stdoutstderr 输出 fixture 。

然后您可以像这样进行检查(改编自文档的示例):

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 fixture 。这将使您能够访问日志级别、记录器等,而不仅仅是文本行。这取决于您提到的依赖于标准库的 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、py.test 和 stderr——从 Cement 日志扩展中捕获日志处理程序输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50935904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com