>sys.s-6ren">
gpt4 book ai didi

python - 丢弃被测程序的标准输出/标准错误,但保留单元测试输出

转载 作者:太空狗 更新时间:2023-10-30 00:44:21 24 4
gpt4 key购买 nike

我有这个示例代码(test_it.py):

import sys

def give_me_5():
print >>sys.stdout, "STDOUT"
print >>sys.stderr, "STDERR"
return 6

import unittest


class TestMe(unittest.TestCase):

def setUp(self):
pass

def test_give_me_5(self):
self.assertEqual(give_me_5(), 5)


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

这给了我以下输出:

» python -m unittest test_it
A long annoying output message
A long annoying error message
F
======================================================================
FAIL: test_give_me_5 (__main__.TestMe)
----------------------------------------------------------------------
Traceback (most recent call last):
File "xx.py", line 17, in test_give_me_5
self.assertEqual(give_me_5(), 5)
AssertionError: 6 != 5

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

但由于被测程序产生的长而烦人的消息(真实程序产生大量输出),我无法看到 unittest 的输出。我想摆脱被测函数的标准输出/标准错误 (give_me_5),但我仍然想看到 unittest 的标准输出/标准错误。我想得到这个结果:

» python -m unittest test_it
F
======================================================================
FAIL: test_give_me_5 (__main__.TestMe)
----------------------------------------------------------------------
Traceback (most recent call last):
File "xx.py", line 17, in test_give_me_5
self.assertEqual(give_me_5(), 5)
AssertionError: 6 != 5

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

这样被测程序产生的输出(包括 stdout 和 stderr)被 unittest 过滤掉,但 unittest 本身产生的输出被保留。我不想修改正在测试的代码(代码本身没有重定向)。我只是想告诉 unittest,所有由被测代码生成的输出到 stdout/stderr 的输出都应该被丢弃。

这可能吗?

最佳答案

@Alik 的建议是正确的。但我想它可以改进。

import sys
# StringIO is replaced in Python 3:
try:
from StringIO import StringIO
except ImportError:
from io import StringIO

class ReplaceStd(object):
""" Let's make it pythonic. """

def __init__(self):
self.stdout = None
self.stderr = None

def __enter__(self):
self.stdout = sys.stdout
self.stderr = sys.stderr

# as it was suggseted already:
sys.stdout = StringIO()
sys.stderr = StringIO()

def __exit__(self, type, value, traceback):
sys.stdout = self.stdout
sys.stderr = self.stderr

print('I am here')
with ReplaceStd():
print('I am not')

print('I am back')

输出:

I am here
I am back

关于python - 丢弃被测程序的标准输出/标准错误,但保留单元测试输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30715337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com