微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在pytest中打印到控制台?

我正在尝试使用pytest进行TDD(测试驱动开发).
使用print时,pytest不会打印到控制台.

我正在使用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.

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

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

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

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

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

解决方法:

认情况下,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 ======================

请注意捕获的标准输出部分.

如果您希望在执行时看到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 ======================

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐