我试着在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时无法获得日志。

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

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

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

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

其他回答

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

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

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

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

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

我通常使用这个命令:-

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

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

我需要打印关于跳过测试的重要警告,正好当PyTest静音字面上的一切。

我不想通过测试来传递一个信号,所以我做了如下修改:

def test_2_YellAboutBrokenAndMutedTests():
    import atexit
    def report():
        print C_patch.tidy_text("""
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.""")
    if sys.stdout != sys.__stdout__:
        atexit.register(report)

atexit模块允许我在PyTest释放输出流之后打印内容。输出如下所示:

============================= test session starts ==============================
platform linux2 -- Python 2.7.3, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /media/Storage/henaro/smyth/Alchemist2-git/sources/C_patch, inifile: 
collected 15 items 

test_C_patch.py .....ssss....s.

===================== 10 passed, 5 skipped in 0.15 seconds =====================
In silent mode PyTest breaks low level stream structure I work with, so
I cannot test if my functionality work fine. I skipped corresponding tests.
Run `py.test -s` to make sure everything is tested.
~/.../sources/C_patch$

Message即使在PyTest处于静默模式时也会被打印,如果使用py运行东西则不会被打印。Test -s,所有东西都已经测试好了。

这是我所知道的打印单个语句到sys的最简洁的方法。Stdout(不人为地使你的测试失败或启用-s选项)-你可以看到你想要的特定输出,仅此:

将内置参数capsys添加到测试函数中。(这意味着您将capsys添加到参数列表中,例如:

def test_function(existing_parameters, capsys):

在你的代码中,只需插入:

with capsys.disabled():
   print("this output will not be captured and go straight to sys.stdout")

参见https://buildmedia.readthedocs.org/media/pdf/pytest/latest/pytest.pdf(2.11如何捕获stdout/stderr输出)。