我试着在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文档,pytest——capture=sys应该可以工作。如果您想在测试中捕获标准,请参考capsys夹具。

其他回答

我最初来到这里是为了找到如何在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"
            ]
        }
    ]
}

默认为py。Test捕获标准输出的结果,以便它可以控制如何打印输出。如果不这样做,它就会输出大量文本,而不知道是什么测试打印了这些文本。

但是,如果测试失败,它将在结果报告中包含一个部分,显示在该特定测试中按照标准输出的内容。

例如,

def test_good():
    for i in range(1000):
        print(i)

def test_bad():
    print('this should fail!')
    assert False

输出结果如下:

>>> py.test tmp.py
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items

tmp.py .F

=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________

    def test_bad():
        print('this should fail!')
>       assert False
E       assert False

tmp.py:7: AssertionError
------------------------------- Captured stdout --------------------------------
this should fail!
====================== 1 failed, 1 passed in 0.04 seconds ======================

注意俘获标准输出部分。

如果您希望在执行语句时看到打印语句,可以将-s标志传递给py.test。但是,请注意,这有时很难解析。

>>> py.test tmp.py -s
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items

tmp.py 0
1
2
3
... and so on ...
997
998
999
.this should fail!
F

=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________

    def test_bad():
        print('this should fail!')
>       assert False
E       assert False

tmp.py:7: AssertionError
====================== 1 failed, 1 passed in 0.02 seconds ======================

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

import warnings

text = "asdf" 

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

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

使用-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