Python unittest:如何临时将 stdout 消息重定向到缓冲区并测试其内容?

Python unittest: How to temporarily redirect stdout messages to a buffer and to test its content?

我想在测试期间临时捕获发送到 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)

我找到了 ,但接受的答案建议捕获发送到 stdout 的所有测试用例的消息。

是的,我知道对发送到标准输出的消息进行单元测试不是很聪明。是的,我也知道将 loggingassertLogs 结合使用会更好。假设现阶段这两个选项都不可用。

解决方案 1. 以下对我有用:

import io
import unittest
from contextlib import redirect_stdout

class Test(unittest.TestCase):
    def test_stdout(self):
        buf = io.StringIO()
        with redirect_stdout(buf):
            print("foo!")
        self.assertIn("foo", buf.getvalue())

buf.getvalue() 将包含整个输出,包括 \n 个字符。

解决方案 2. 要模仿 assertLogs 的行为,可以通过方法 assertStdout 扩展 unittest.TestCase,如下所示。

class StdoutRedirectionContext():
    class ListIO():
        def __init__(self):
            # Container for messages sent to stdout.
            self.output = []
        def write(self, s):
            # Filter empty strings or naked newline characters.
            if s in ("\n", ""): return
            self.output.append(s)

    def __enter__(self):
        self._buf = self.ListIO()
        self._ctx = redirect_stdout(self._buf)
        self._ctx.__enter__()
        return self._buf

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self._ctx.__exit__(exc_type, exc_value, exc_traceback)

class TestCase(unittest.TestCase):
    def assertStdout(self):
        return StdoutRedirectionContext()

这里,StdoutRedirectionContext充当上下文管理器,单个消息将收集在output列表中。扩展的 TestCase 可以按如下方式用于在 stdout 上断言消息:

class AnotherTest(TestCase):
    def test_stdout(self):
        with self.assertStdout() as cm:
            print("foo!")
            print("bar!")
        self.assertIn("foo!", cm.output)
        self.assertIn("baz!", cm.output)

以上产生以下输出:

======================================================================
FAIL: test_stdout (__main__.AnotherTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "executor_test.py", line 440, in test_stdout
    self.assertIn("baz!", cm.output)
AssertionError: 'baz!' not found in ['foo!', 'bar!']