【问题标题】:Python, py.test and stderr -- capturing logging handler output from Cement logging extensionPython、py.test 和 stderr——从 Cement 日志扩展中捕获日志处理程序输出
【发布时间】:2018-06-19 19:48:16
【问题描述】:

我已经用 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 输出时,不会捕获任何内容(re: 在上述代码中将'stdout' 替换为'stderr')。我看到了一种通过标准 Python 日志记录处理程序来查找输出的方法,我怀疑类似的东西会被使用Cement 日志扩展来捕获stderr,但我无法弄清楚。有人有什么见解吗?

【问题讨论】:

    标签: python logging pytest stderr cement


    【解决方案1】:

    捕获stdoutstderr 输出可以使用capsys 夹具完成。

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

    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
    

    【讨论】:

    • 感谢塞缪尔。我在传递参数时遇到问题,不得不重做测试。现在效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多