如何在Py Test中打印到控制台?

BBe*_*dit 139 python unit-testing pytest python-2.7

我正在尝试使用pytest模块进行测试驱动开发.pytest我写的时候pytest不会到控制台print.

我用print它来运行它...

pytest my_tests.py似乎是说,它应该是默认的工作:http://pytest.org/latest/capture.html

但:

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.
Run Code Online (Sandbox Code Playgroud)

什么都没有打印到我的标准输出控制台(只是正常的进度和多少次测试通过/失败).

我正在测试的脚本包含print:

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

documentation模块中,默认情况下会打印所有内容,这正是我需要的.但是,我希望unittest出于其他原因使用.它似乎是这样的基本功能,也许我很想念它!?

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

tbe*_*lay 167

默认情况下,py.test捕获标准输出的结果,以便它可以控制打印输出的方式.如果它没有这样做,它会喷出很多文本而没有测试打印该文本的上下文.

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

例如,

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

def test_bad():
    print('this should fail!')
    assert False
Run Code Online (Sandbox Code Playgroud)

结果如下:

>>> 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 ======================
Run Code Online (Sandbox Code Playgroud)

请注意该Captured stdout部分.

如果您希望print在执行时看到语句,可以将-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 ======================
Run Code Online (Sandbox Code Playgroud)

  • 嗯...仍然没有记录我的打印语句 (6认同)
  • 对我不起作用 (3认同)
  • 非常实用。做得好! (2认同)

Sac*_*cha 59

这是我所知道的打印单个语句的最干净的方法sys.stdout(不会人为地使您的测试失败或启用该-s选项) - 您可以看到您想要的特定输出,仅此而已:

  1. 将内置参数添加capsys到您的测试函数中。(这意味着您添加capsys到参数列表中,例如
def test_function(existing_parameters, capsys):
Run Code Online (Sandbox Code Playgroud)
  1. 在您的代码中,只需插入:
with capsys.disabled():
   print("this output will not be captured and go straight to sys.stdout")
Run Code Online (Sandbox Code Playgroud)

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

  • 这应该是首选答案!它似乎完美无缺地工作,没有副作用。 (4认同)
  • 这样我就可以看到我的打印日志。我没有通过 -s 选项或创建文件看到打印日志。 (2认同)

dmi*_*nov 49

使用-s选项将打印所有功能的输出,这可能太多了.

如果您需要特定输出,您提到的文档页面提供的建议很少:

  1. assert False, "dumb assert to make PyTest print my stuff"在函数末尾插入,由于测试失败,您将看到输出.

  2. 您有PyTest传递给您的特殊对象,您可以将输出写入文件以便稍后检查,例如

    def test_good1(capsys):
        for i in range(5):
            print i
        out, err = capsys.readouterr()
        open("err.txt", "w").write(err)
        open("out.txt", "w").write(out)
    
    Run Code Online (Sandbox Code Playgroud)

    您可以在单独的选项卡中打开outerr文件,让编辑器自动为您刷新它,或者执行一个简单的py.test; cat out.txtshell命令来运行测试.

这是做事的相当黑客的方式,但可能是你需要的东西:毕竟,TDD意味着你把东西弄得乱七八糟,当它准备好时保持干净和安静:-).


lmi*_*asf 23

简短答案

使用-s选项:

pytest -s
Run Code Online (Sandbox Code Playgroud)

详细答案

文档

在执行测试期间,将捕获发送到stdoutstderr的所有输出。如果测试或设置方法失败,则通常会显示其相应的捕获输出以及失败回溯。

pytest具有选项--capture=method,其中method是每个测试捕获方法,并且可以是下列之一:fdsysnopytest还具有-s是的快捷方式--capture=no的选项,该选项使您可以在控制台中查看打印语句。

pytest --capture=no     # show print statements in console
pytest -s               # equivalent to previous command
Run Code Online (Sandbox Code Playgroud)

设置捕获方法或禁用捕获

有两种pytest执行捕获的方法:

  1. 文件描述符(FD)级别捕获(默认):将捕获对操作系统文件描述符1和2的所有写操作。

  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
Run Code Online (Sandbox Code Playgroud)


dmi*_*nov 12

我需要打印关于跳过测试的重要警告,确切地说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)
Run Code Online (Sandbox Code Playgroud)

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$
Run Code Online (Sandbox Code Playgroud)

即使PyTest处于静音模式也会打印消息,如果您运行的话,则不会打印消息py.test -s,因此所有内容都已经过很好的测试.

  • 非常适合输出自定义测试指标。 (2认同)

小智 6

根据pytest文档,pytest --capture=sys应该工作.如果要在测试中捕获标准输出,请参阅capsys fixture.

  • 要在每次运行“pytest”时传递“--capture”选项,请在文件“pytest.ini”中的“[pytest]”部分添加行“addopts = --capture=tee-sys”([文档](https://docs.pytest.org/en/latest/reference/customize.html#pytest-ini))。 (3认同)

小智 5

不会人为地使您的测试失败或启用该-s选项

import warnings

text = "asdf" 

warnings.warn(UserWarning("{}".format(text)))
Run Code Online (Sandbox Code Playgroud)