答案中的@Acumenus说:
它还使用了一个可重用的辅助方法 assert_stdout,尽管这个辅助方法是特定于被测试的函数的。
粗体部分似乎有一些缺点,因此我会做以下操作:
class TestCase(unittest.TestCase):
def assertStdout(self, expected_output):
return _AssertStdoutContext(self, expected_output)
def assertPrints(self, *expected_output):
expected_output = "\n".join(expected_output) + "\n"
return _AssertStdoutContext(self, expected_output)
class _AssertStdoutContext:
def __init__(self, testcase, expected):
self.testcase = testcase
self.expected = expected
self.captured = io.StringIO()
def __enter__(self):
sys.stdout = self.captured
return self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = sys.__stdout__
captured = self.captured.getvalue()
self.testcase.assertEqual(captured, self.expected)
这使得内容更易于理解和重复使用:
class TestPrint(TestCase):
def test_print1(self):
with self.assertStdout("test\n"):
print("test")
通过使用简单的上下文管理器。(可能还需要将
"\n"
附加到
expected_output
,因为
print()
默认添加换行符。请参见下一个示例...) 此外,这是一种非常好的变体(适用于任意数量的打印!)
def test_print2(self):
with self.assertPrints("test1", "test2"):
print("test1")
print("test2")
现在是可能的。
foo
接受大约8个参数,并返回一个json。我也想测试这个。 - sudhishkr