禁止来自Python / unittest的所有输出

时间:2018-12-06 18:16:02

标签: python shell unit-testing

我正在尝试禁止python的unittest的 ALL 终端输出,并希望仅根据测试是否通过来给出自定义反馈。我在网上发现的所有内容似乎都无效。我的用例是向学习Python的新学生提供反馈/提示。

我正在用我的shell脚本调用unittest(我尝试了“ dev / null”的几种变体):

if python -m unittest discover -s test; then
    echo "<div class='pass'>pass</div>"
else
    echo "<div class='fail'>fail</div>"
fi >>/dev/null

下面是我的python unittest文件:

import unittest
import sys
import os

sys.path.insert(0, '/path/to/module')
import myFile

sys.stdout = os.devnull //tried this but didn't work
sys.stderr = os.devnull //tried this but didn't work

class TestCalc(unittest.TestCase):

  def test_add(self):
    result = calc.add(10, 5)
    self.assertEqual(result, 15)

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

事实上,我的shell脚本中的回显是否根据测试是否通过而运行,但是最重要的是我不需要的所有终端输出。 (输出在我运行时是在交互式IDE中)

附录:我无法找到任何unittest可选参数来抑制所有输出。

1 个答案:

答案 0 :(得分:0)

另一种选择(除了像Daniel Pryden所建议的那样编写自己的TestRunner之外)是简单地从命令行包装对测试可执行文件的调用并过滤掉(例如,使用grep,{{ 1}},awk或其他perl脚本)仅显示要显示的部分。