我试着在pytest中使用TDD(测试驱动开发)。 当我使用print时,pytest将不会打印到控制台。

我使用pytest my_tests.py来运行它。

文档似乎说默认情况下它应该工作:http://pytest.org/latest/capture.html

But:

import myapplication as tum

class TestBlogger:

    @classmethod
    def setup_class(self):
        self.user = "alice"
        self.b = tum.Blogger(self.user)
        print "This should be printed, but it won't be!"

    def test_inherit(self):
        assert issubclass(tum.Blogger, tum.Site)
        links = self.b.get_links(posts)
        print len(links)   # This won't print either.

我的标准输出控制台没有输出任何内容(只有正常的进度以及通过/失败的测试数量)。

我正在测试的脚本包含打印:

class Blogger(Site):
    get_links(self, posts):
        print len(posts)   # It won't get printed in the test.

在unittest模块中,默认情况下打印所有内容,这正是我所需要的。但是,出于其他原因,我希望使用pytest。

有人知道如何显示打印语句吗?


当前回答

我通常使用这个命令:-

pytest -v -rs --html=report.html --self-contained-html test_Suite.py -s

上面的命令还生成了一个report.html文件,其中捕获并保存了所有打印语句。最后的-s也会显示打印语句到终端。

其他回答

使用-s选项:

pytest -s

详细的回答

从文档中可以看出:

在测试执行期间,任何发送到stdout和stderr的输出都会被捕获。如果测试或设置方法失败,通常会显示其相应的捕获输出以及失败回溯。

Pytest有选项——capture=method,其中method是每测试捕获方法,可以是以下之一:fd, sys或no。Pytest还有选项-s,这是——capture=no的快捷方式,这个选项将允许您在控制台中查看打印语句。

pytest --capture=no     # show print statements in console
pytest -s               # equivalent to previous command

设置捕获方法或禁用捕获

pytest执行捕获有两种方式:

文件描述符(FD)级别捕获(默认):所有写入操作系统文件描述符1和2的操作都将被捕获。 sys级捕获:只写入Python文件sys。Stdout和sys。Stderr将被捕获。不执行对文件描述符的写操作。

pytest -s            # disable all capturing
pytest --capture=sys # replace sys.stdout/stderr with in-mem files
pytest --capture=fd  # also point filedescriptors 1 and 2 to temp file

根据pytest文档,pytest——capture=sys应该可以工作。如果您想在测试中捕获标准,请参考capsys夹具。

如果你正在使用pytest.ini,考虑使用:

[pytest]
...
addopts = --capture=no
...

如果你从一个基于pytest.ini的IDE扩展运行测试,这工作得很好

已经有很多很好的答案,但我想分享一下为什么在运行pytest时无法获得日志。

一个重要的注意事项是,当您编写函数时,每个测试用例必须以test_前缀开始。否则,在使用pytest时就不会有打印语句。

至于命令,我使用下面的命令来获得非常全面的日志:

python -m pytest -v -rs <particular_file.py> -s -o log_cli-level=DEBUG

通过确保您有正确的函数名并使用我的命令,您应该能够确定地看到控制台日志。

你也可以通过Pycharm GUI来设置:去运行>编辑配置。在那里,选择要为其启用打印语句的测试,并在Additional Arguments字段中添加-s。

我这样做是因为虽然我主要使用Pycharm调试器来调试我的pytest函数(即通过GUI),但我的特定用例也要求我知道代码中其他地方发生了什么,打印语句可以为此派上用场。