我试着在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

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

其他回答

这是我所知道的打印单个语句到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输出)。

无需人为地使测试失败或启用-s选项

import warnings

text = "asdf" 

warnings.warn(UserWarning("{}".format(text)))

我需要打印关于跳过测试的重要警告,正好当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,所有东西都已经测试好了。

我最初来到这里是为了找到如何在VSCode的控制台中打印PyTest,同时从那里运行/调试单元测试。这可以通过下面的启动来完成。json配置。给定虚拟环境文件夹.venv。

    "version": "0.2.0",
    "configurations": [
        {
            "name": "PyTest",
            "type": "python",
            "request": "launch",
            "stopOnEntry": false,
            "pythonPath": "${config:python.pythonPath}",
            "module": "pytest",
            "args": [
                "-sv"
            ],
            "cwd": "${workspaceRoot}",
            "env": {},
            "envFile": "${workspaceRoot}/.venv",
            "debugOptions": [
                "WaitOnAbnormalExit",
                "WaitOnNormalExit",
                "RedirectOutput"
            ]
        }
    ]
}

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