我想捕获在测试期间临时发送到stdout
(我们的stderr
)的消息,并断言这些消息中是否出现了某些字符串模式:
import unittest
class SomeTest(unittest.TestCase):
def test_stdout(self):
output = ""
function_that_writes_to_stdout()
# How to capture stdout in output temporarily?
self.assertIn("some message", output)
我发现了一个similar question,但是公认的答案建议捕获所有测试用例发送到stdout
的消息。你知道吗
是的,我知道对发送到stdout的消息进行单元测试不是很明智。是的,我也知道最好将logging
与^{
解决方案1。以下方法对我有效:
buf.getvalue()
将包含整个输出,包括\n
字符。你知道吗解决方案2.为了模拟^{} 的行为,可以通过如下方法
assertStdout
扩展unittest.TestCase
。你知道吗这里,
StdoutRedirectionContext
充当上下文管理器,单个消息将被收集在output
列表中。扩展的TestCase
可以如下所示在stdout上断言消息:以上结果产生以下输出:
相关问题 更多 >
编程相关推荐