【问题标题】:Suppress print output in unittests禁止单元测试中的打印输出
【发布时间】:2014-07-30 19:45:57
【问题描述】:

编辑:请注意我使用的是 Python 2.6(已标记)

假设我有以下内容:

class Foo:
    def bar(self):
        print 'bar'
        return 7

假设我有以下单元测试:

import unittest
class ut_Foo(unittest.TestCase):
    def test_bar(self):
        obj = Foo()
        res = obj.bar()
        self.assertEqual(res, 7)

所以如果我跑:

unittest.main()

我明白了:

bar # <-- I don't want this, but I *do* want the rest
.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK
Exit code:  False

我的问题是:有没有办法抑制正在测试的对象的输出,同时仍然获得 unittest 框架的输出?

编辑 这个问题不是 flagged question 的重复问题,flagged question 询问关于在普通 python 脚本中使特定函数的标准输出静音。

而这个问题是关于在运行它的单元测试时隐藏 python 脚本的正常标准输出。我仍然希望显示 unittest 标准输出,并且我不想禁用我测试脚本的标准输出。

【问题讨论】:

标签: python python-2.6 python-unittest


【解决方案1】:

使用选项“-b”调用您的单元测试 - 缓冲区标准输出和标准错误

Foo.py

class Foo:
    def bar(self):
        print "bar"
        return 7

test.py

import unittest
from Foo import Foo

class test_Foo(unittest.TestCase):
    def test_bar(self):
        obj = Foo()
        res = obj.bar()
        self.assertEqual(res, 7)

if __name__ == "__main__":
    unittest.main()

使用 -b 选项运行它

$ python test.py -b
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

替代方案:使用nose

$ pip install nose

什么安装命令nosetests

注意,我已经修改了测试套件,使其具有以test 为前缀的类和方法,以满足nose 默认测试发现规则。

nosetests 默认不显示输出

$ nosetests
.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK

如果要查看输出,请使用-s 开关:

$ nosetests -s
bar
.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK

【讨论】:

  • 您也可以使用unittest.main(buffer=True) 将其设为默认值
  • 这适用于 python 2.7 但是我询问了 python 2.6,遗憾的是它不支持这个选项。
  • @user2016436 抱歉,我没有注意您问题的所有(非常明确的)细节。你是对的,buffer 选项是在 Python 2.7 中添加的,而在 Python 2.6 中是缺失的。但是,nose 解决方案应该可以工作(即使角落情况可能略有不同)
  • 请注意,-b 有助于抑制 python 打印语句,但不能从代码调用的二进制文件输出,例如使用 subprocess.run。
【解决方案2】:

您可以通过禁用 sys.stdout 并在测试完成后启用它来抑制输出:

import sys
import io
import unittest

class ut_Foo(unittest.TestCase):
    def test_bar(self):

        #You suppress here:
        suppress_text = io.StringIO()
        sys.stdout = suppress_text 
        
        obj = Foo()
        res = obj.bar()
        self.assertEqual(res, 7)
        
        #You release here:
        sys.stdout = sys.__stdout__

所有这些都来自:

https://codingdose.info/2018/03/22/supress-print-output-in-python/

【讨论】:

  • 我发现使用with statment 和一个模拟,更好的语法,例如:with mock.patch('sys.stdout', new = StringIO()) as std_out:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
  • 2020-06-19
  • 1970-01-01
  • 2012-02-09
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多